Skip to content
FlagSwiftDocs

Integrate with React

Hooks and a provider for single-page apps.

Before you start#

  • A client key (fs_client_…) from the API Keys page of your console. See API keys for how keys differ.
  • The address of your FlagSwift server, for example https://flags.example.com.
  • A flag to read. Create one in the console and turn it on in an environment.

Only client keys belong in an app people can inspect

Server and admin keys can read targeting and rollout data. Use a client key for anything that ships to a browser or a phone.

Your server#

Enter your server address and, if your key covers every environment of the project, the environment to read. The examples below fill in as you type. Nothing is sent anywhere: the values stay in this browser.

Set up#

  1. Environment

    bash
    NEXT_PUBLIC_FLAGSWIFT_KEY=fs_client_...   # from the API Keys page
  2. Install

    bash
    npm install @flagswift/react
  3. Set up

    tsx
    import { FlagClient, FlagProvider } from "@flagswift/react";
    
    // Create the client once, outside components.
    const client = new FlagClient({
      apiKey: process.env.NEXT_PUBLIC_FLAGSWIFT_KEY!,
      baseUrl: "https://flags.example.com",
    });
    
    export const Providers = ({ children }: { children: React.ReactNode }) => (
      <FlagProvider client={client} user={{ identifier: user?.id, account: user?.orgId }}>
        {children}
      </FlagProvider>
    );
  4. Use

    tsx
    import { useFlag } from "@flagswift/react";
    
    export const Dashboard = () => (useFlag("new-dashboard") ? <NewDashboard /> : <OldDashboard />);

Verify it works#

Before you run your app, check the key, the address and the environment with one request. A client key reads the outcome for one person.

bash
curl -s -X POST "https://flags.example.com/api/v1/evaluation/client" \
  -H "Authorization: Bearer $FLAGSWIFT_CLIENT_KEY" \
  -H "Content-Type: application/json" \
  -d '{"identifiers":["user-123"]}'

A 200 response with your flags means everything is wired up. If it fails, Troubleshooting lists the usual causes.

Next steps#