Meta-framework SDKs

Next.js SDK

Evaluate configs and feature flags in the browser, in server routes, and during SSR with the Next.js SDK

Introduction

The Next.js SDK combines a client and a server SDK to provide configs to the browser, to server routes, and to SSR. It is intended to be used by Next.js web applications running on modern web browsers. All modern web browsers on popular platforms should be supported.

The minimum supported version of Next.js is 14.0.

Browser SDKs are tested on the latest versions of Chrome, Firefox, Safari, and Edge.

Telemetry collection within the browser uses Web Workers to aggregate and send telemetry data. If the SDK runs on older browsers without Web Workers support, config evaluation will continue to work but no telemetry data will be collected for that session.

Installation

The SDK can be installed from NPM: https://www.npmjs.com/package/@configdirector/nextjs-sdk

npm install --save @configdirector/nextjs-sdk

Configure the SDK

Set up the server instance to initialize at startup

The Next.js SDK maintains a singleton server SDK instance used in server routes and server side rendering (SSR). In order to register this instance at startup, you can make use of the Next.js instrumentation.ts file:

instrumentation.ts
export async function register() {
  const { register } = await import("@configdirector/nextjs-sdk/server");
  await register({
    // The server SDK key is a secret value, do not commit it to your source code repository.
    // In this example, we are assuming the environment variable CONFIGDIRECTOR_SERVER_SDK_KEY
    // will be populated at runtime with your server SDK key in the server environment
    serverSdkKey: process.env["CONFIGDIRECTOR_SERVER_SDK_KEY"]!,
  });
}

If you are using a version of Next.js older than 15, instrumentation is an experimental feature that must be enabled explicitly:

next.config.js
module.exports = {
  experimental: {
    instrumentationHook: true,
  },
};

Configure the client provider

The ConfigDirector hooks are only available within a ConfigDirectorProvider. The simplest approach is to wrap your application in a ConfigDirectorProvider in your layout. There are a couple of options for this.

Using a dynamic layout and a server-side environment variable for the client key:

app/layout.tsx
import { ConfigDirectorProvider } from "@configdirector/nextjs-sdk/server";
import type { ReactNode } from "react";

export const dynamic = "force-dynamic";

export default async function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>
        <ConfigDirectorProvider sdkKey={process.env["CONFIGDIRECTOR_CLIENT_SDK_KEY"]!}>
          <main>{children}</main>
        </ConfigDirectorProvider>
      </body>
    </html>
  );
}

force-dynamic makes the layout read the environment variable on every request, so one build can be deployed to several environments. The trade-off is that the pages lose static generation. If you build once per environment instead, you can leave force-dynamic out: the environment variable set at build time is baked into that build's static output.

Do not use a NEXT_PUBLIC_ environment variable for the SDK key, even in a static layout. Next.js replaces every NEXT_PUBLIC_ reference with its build-time value, which freezes the key into the build and exposes it to all browser code. A plain environment variable reaches the browser only through the provider.

Additionally, you can configure the provider with a context. In this example, we retrieve the userId from a cookie:

app/layout.tsx
import { ConfigDirectorProvider } from "@configdirector/nextjs-sdk/server";
import type { ReactNode } from "react";
import { cookies } from "next/headers";

export const dynamic = "force-dynamic";

export default async function RootLayout({ children }: { children: ReactNode }) {
  const userId = (await cookies()).get("userId")?.value;
  return (
    <html lang="en">
      <body>
        <ConfigDirectorProvider
          sdkKey={process.env["CONFIGDIRECTOR_CLIENT_SDK_KEY"]!}
          context={{ id: userId }}>
          <main>{children}</main>
        </ConfigDirectorProvider>
      </body>
    </html>
  );
}

Additional configuration options

appName and appVersion

These metadata options allow you to provide your application's name and version. These values can be used in targeting rules conditionals. For example, if a certain feature should only be enabled starting with a certain version of your application.

instrumentation.ts
export async function register() {
  const { register } = await import("@configdirector/nextjs-sdk/server");
  await register({
    serverSdkKey: process.env["CONFIGDIRECTOR_SERVER_SDK_KEY"]!,
    metadata: {
      appName: "YOUR-APP-NAME",
      appVersion: "1.0.2",
    },
  });
}

The appName and appVersion are automatically propagated to the client SDK instance via the ConfigDirectorProvider RSC. However, if needed they can be overridden to a different value when configuring the provider as well:

app/layout.tsx
import { ConfigDirectorProvider } from "@configdirector/nextjs-sdk/server";
import type { ReactNode } from "react";

export default async function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>
        <ConfigDirectorProvider
          sdkKey={process.env["CONFIGDIRECTOR_CLIENT_SDK_KEY"]!}
          appName="A-DIFFERENT-APP-NAME"
          appVersion="1.0.3">
          <main>{children}</main>
        </ConfigDirectorProvider>
      </body>
    </html>
  );
}

logger (server only)

By default, the SDK on the server side logs to the console and it is set to log warnings and errors only. You can configure a logger by either creating a ConfigDirector console logger with a different log level, or by implementing the ConfigDirectorLogger interface to provide your own logger. The interface can be used to create an adapter to another logging library.

Configure the ConfigDirector console logger to a different level:

instrumentation.ts
export async function register() {
  const { register, createConsoleLogger } = await import("@configdirector/nextjs-sdk/server");
  await register({
    serverSdkKey: process.env["CONFIGDIRECTOR_SERVER_SDK_KEY"]!,
    logger: createConsoleLogger("info"),
  });
}

Implement your own logger adapter:

instrumentation.ts
import type { ConfigDirectorLogger } from "@configdirector/nextjs-sdk/server";

export async function register() {
  const { register } = await import("@configdirector/nextjs-sdk/server");
  const myLogger: ConfigDirectorLogger = {
    debug: function (message: string, ...args: any): void {
      // your specific logging library implementation here
    },
    info: function (message: string, ...args: any): void {
      // your specific logging library implementation here
    },
    warn: function (message: string, ...args: any): void {
      // your specific logging library implementation here
    },
    error: function (message: string, ...args: any): void {
      // your specific logging library implementation here
    },
  };

  await register({
    serverSdkKey: process.env["CONFIGDIRECTOR_SERVER_SDK_KEY"]!,
    logger: myLogger,
  });
}

logLevel (client only)

The SDK on the client side logs to the browser console. You can adjust the ConfigDirector's SDK logging level for the client side via the logLevel option (defaults to warn):

app/layout.tsx
import { ConfigDirectorProvider } from "@configdirector/nextjs-sdk/server";
import type { ReactNode } from "react";

export default async function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>
        <ConfigDirectorProvider
          sdkKey={process.env["CONFIGDIRECTOR_CLIENT_SDK_KEY"]!}
          logLevel="info">
          <main>{children}</main>
        </ConfigDirectorProvider>
      </body>
    </html>
  );
}

mode, pollingInterval and values (client only)

The connection mode of the client-side provider, one of streaming, polling or offline. It is recommended to use the default of streaming unless you have a specific need to use polling instead. pollingInterval is the interval, in seconds, between requests for config updates when mode is polling, and has no effect in the other modes. It defaults to 60 seconds, and a value below the minimum of 30 seconds is raised to 30 seconds and a warning is logged. See Polling intervals. In offline mode the browser never connects to ConfigDirector and serves the values you give it, one value per config key; see Run without a connection. The browser half keeps the last values it received on the device by default and serves them on the next page load of the same context until live values arrive, as the JavaScript SDK does.

app/layout.tsx
import { ConfigDirectorProvider } from "@configdirector/nextjs-sdk/server";
import type { ReactNode } from "react";

export default async function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>
        <ConfigDirectorProvider
          sdkKey={process.env["CONFIGDIRECTOR_CLIENT_SDK_KEY"]!}
          mode="polling"
          pollingInterval={120}>
          <main>{children}</main>
        </ConfigDirectorProvider>
      </body>
    </html>
  );
}

deferInitialization (client only)

By default, the browser connects to ConfigDirector as soon as the page has rendered, with the context the provider has at that point: the context prop, or one given through updateContext while the page first renders. An application that learns its context only after an asynchronous step in the browser, such as client-side authentication, therefore opens a first connection with no context and a second one once it calls updateContext. The visitor of that first connection counts as a monthly active user in addition to the signed-in user, and the values kept on the device for the signed-in user are not served until the second connection opens.

Turn on deferInitialization to make the browser wait for its first context instead:

app/layout.tsx
import { ConfigDirectorProvider } from "@configdirector/nextjs-sdk/server";
import type { ReactNode } from "react";

export default async function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>
        <ConfigDirectorProvider
          sdkKey={process.env["CONFIGDIRECTOR_CLIENT_SDK_KEY"]!}
          deferInitialization>
          <main>{children}</main>
        </ConfigDirectorProvider>
      </body>
    </html>
  );
}

With the prop on, nothing connects and nothing is sent until the provider is given a context, through the context prop or an updateContext call. Until then, useConfigDirectorStatus reports loading and the hooks return the values the page was rendered with on the server, or the in-code default values. The first context opens one connection that carries it: the values kept on the device for that context are served until live values arrive, and the status becomes ready, or default when the connection timeout passes without values, as at startup without the prop. Later contexts update the context as usual.

A context given while the page first renders, through the prop or an effect that runs when a component mounts, starts the browser right away, as it does without the prop. A page that never gives a context never connects and stays loading, showing the server-rendered values or the in-code default values, so turn the prop on only when every page that reads configs gives a context. The prop has no effect in offline mode, where the browser is ready at once with its values.

Additional server configuration

The register function accepts the same configuration values as the Node.js server SDK. You can refer to the Node.js SDK for a full list of those configuration options. The server instance uses the server SDK polling defaults: connection.pollingInterval defaults to 300 seconds with a minimum of 60 seconds. serverSdkKey is required unless the connection mode is offline.

Run without a connection

Set the connection mode to offline to run your application without connecting to ConfigDirector, for example in a matrix of UI tests where each cell pins every flag to a known value. Neither the server nor the browser needs an SDK key, no connection is opened and nothing is sent, so the application is invisible to the ConfigDirector dashboard: no evaluations are counted and no lifecycle state changes. Every context receives the same value and targeting rules are not applied.

Give the values once, to the server half, in a JSON file with one value per config key. Your application decides where the path comes from; here instrumentation.ts reads an environment variable of the application's own:

instrumentation.ts
export async function register() {
  const { register } = await import("@configdirector/nextjs-sdk/server");
  const file = process.env["CONFIGDIRECTOR_OFFLINE_FILE"];
  await register(
    file
      ? { connection: { mode: "offline", file } }
      : { serverSdkKey: process.env["CONFIGDIRECTOR_SERVER_SDK_KEY"]! },
  );
}
flags/new-checkout-on.json
{
  "new-checkout": true,
  "max-items": 20,
  "greeting": "hello",
  "theme": { "color": "blue" }
}
CONFIGDIRECTOR_OFFLINE_FILE=./flags/new-checkout-on.json next start

The file path is resolved against the process working directory, and the values can also be given inline as connection.values instead of a file. The config type of each value follows from the value itself: a boolean, an integral number (integer), any other number (float), a string, or an object or array (json). A value read with an in-code default value of another type returns the in-code default value, as it does against ConfigDirector.

The layout does not change between a live run and an offline run. When register() ran in offline mode, the server ConfigDirectorProvider hands the server's values to the browser half, which serves them in offline mode too, so server-rendered pages, hydration and the browser show the same values, and sdkKey can be left out. Give the provider its own mode and values props to override this; then the browser half serves those instead, whatever mode the server runs in, and the server half serves its own, with no check that the two agree. An application that renders the client ConfigDirectorProvider without the server one gives it mode="offline" and values itself.

With mode: "offline" and neither file nor values, the server is ready at once and every config returns its in-code default value on both halves.

register() rejects with a ConfigDirectorInitializationError, which the SDK exports, when the values cannot be loaded: the file is missing, cannot be read, is not a JSON object or holds a value such as null; file and values are both given; or either is given in streaming or polling mode. The server does not start, so a test cell with a misspelled path fails instead of passing on in-code default values. useConfigDirectorStatus reports loading during server rendering and hydration and ready as soon as the provider mounts. pollingInterval, timeout and url have no effect.

A page prerendered at build time carries the values present at build time. For a test matrix, either build once per cell or keep force-dynamic on the layout so every request reads the running server's values.

If you come from LaunchDarkly, a file of values is what LaunchDarkly calls "flags from files", and offline with no values is its "offline mode".

Retrieve config values

In your client components, retrieve a config value with the useConfigValue hook. On the server side, getConfigClient returns the global server instance of the client (an instance of the Node.js SDK).

Retrieving config values in client components:

YourComponent.tsx
"use client";

import { useConfigValue } from "@configdirector/nextjs-sdk/client";

function YourComponent() {
  const { value } = useConfigValue("my-config-key", false);

  return (<p>my-config-key: {value}</p>);
}

export default YourComponent;

Retrieving config values in server routes:

route.ts
import { getConfigClient } from "@configdirector/nextjs-sdk/server";

export async function GET() {
  const client = getConfigClient();
  const value = client.getValue("my-config-key", false);
  return Response.json({ "my-config-key": value });
}

evaluate

Both halves can return the evaluation behind a value instead of the value alone: the value, whether it is the in-code default value, the reason, the valueId, and the variation. In client components, the client from the useClient hook of @configdirector/nextjs-sdk/client has evaluate(key, defaultValue), as described for the JavaScript SDK. The browser client exists only once the provider has mounted in the browser, and useClient throws before that, including during server rendering, so render a component that calls it only when useConfigDirectorStatus no longer reports loading. On the server, the client from getConfigClient has evaluate(key, defaultValue, context), with the context optional as in getValue, as described for the Node.js SDK. Use it where the reason matters at the point of the read, such as when reporting an evaluation to another system. Both entry points export the ConfigEvaluation, EvaluationReason and Variation types. evaluate is available from version 1.13.0 of the SDK, and its variation from version 1.14.0.

route.ts
import { getConfigClient } from "@configdirector/nextjs-sdk/server";

export async function GET() {
  const evaluation = getConfigClient().evaluate("new-checkout", false, { id: "user-id" });
  return Response.json({ newCheckout: evaluation.value, reason: evaluation.reason });
}

track

Both halves report to ConfigDirector that something happened, such as a completed checkout, so ConfigDirector can show it on the Live feed and count it for each variation of a running experiment. In client components, the client from useClient has track(eventName, options), which reports the event for the browser's current context, as described for the JavaScript SDK. On the server, the client from getConfigClient has track(eventName, context, options), with the context and the options optional, as described for the Node.js SDK. An event counts for an experiment only when it carries the id of the context the experiment's config was evaluated for, so on the server pass the context you evaluate with. track is available from version 1.14.0 of the SDK.

route.ts
import { getConfigClient } from "@configdirector/nextjs-sdk/server";

export async function POST() {
  const order = await completeCheckout();
  getConfigClient().track("checkout-completed", { id: order.userId }, { value: order.total });
  return Response.json({ orderId: order.id });
}

SSR config evaluation

Evaluation of config values during server side rendering (SSR) utilizes the global server instance of the ConfigDirector Node.js client. That means there are no additional network requests that take place since the server SDK evaluates targeting rules locally for any given context.

For SSR to work correctly, configs need to be made available to both, the client and the server, in the ConfigDirector dashboard.

On the server, a context without an id skips percentage rollouts: the targeting rules after the rollout are tried, and the default targeting rule value is served when none of them applies, as described for the Node.js SDK. In the browser, such a visitor stays in a rollout through the instance ID the SDK keeps. When a visitor who has not signed in should get the same rollout value from server rendering and in the browser, give the context the same id on both sides, such as a session ID from a cookie. Versions 1.14.0 and 1.14.1 of the SDK ended the evaluation at the skipped rollout on the server, and versions before 1.14.0 served every context without an id the first share of the rollout.

Update the context

The browser connects with the context given to the provider's context prop. Give it there when the page loads, for example from a cookie read in the root layout as shown in Configure the client provider, so the first connection carries it.

To change the context afterwards, for example when a user signs in, call updateContext from the useContext hook where the change happens:

YourComponent.tsx
"use client";

import { useConfigValue, useContext } from "@configdirector/nextjs-sdk/client";

function YourComponent() {
  const { value } = useConfigValue("my-config-key", false);
  const { updateContext } = useContext();

  const onUpdate = async () => {
    await updateContext({
      id: "654321",
      name: "Another User",
      traits: {
        region: "Australia",
      },
    });
  };

  return (
    <div>
      <p>my-config-key: {String(value)}</p>
      <button type="button" onClick={onUpdate}>
        Update context
      </button>
    </div>
  );
}

export default YourComponent;

Rendering the provider with a different context prop updates the context the same way.

A context given while the page first renders goes out with the first connection, whether it comes from the provider's context prop or from an updateContext call in an effect that runs when a component mounts: the browser connects once the page's first render and its effects are done. updateContext is the same function on every render, so it is safe to list in an effect's dependencies. A context equal to the one the provider already has, given through the prop or through updateContext, opens no new connection.

On server routes, the context is provided at evaluation time as the third argument to getValue. Unlike client SDKs, the server SDKs are able to evaluate targeting rules for the given context locally without additional network calls.

route.ts
import { getConfigClient } from "@configdirector/nextjs-sdk/server";

export async function GET() {
  const client = getConfigClient();
  const value = client.getValue("my-config-key", false, {
    id: "654321",
    name: "Another User",
    traits: {
      region: "Australia",
    },
  });
  return Response.json({ "my-config-key": value });
}

To evaluate configs for an entity other than a user, such as a tenant, set the context kind with kind. It works the same in updateContext and in getValue:

route.ts
const value = client.getValue("my-config-key", false, {
  id: "acme",
  kind: "tenant",
  name: "Acme Inc.",
  traits: {
    plan: "enterprise",
  },
});

Leaving kind out means user. A context kind is 1 to 64 lowercase letters, digits, dashes, or underscores. A context with an invalid context kind is ignored: the SDK logs an error, and configs are evaluated as if no context had been given. Context kinds are available from version 1.10.0 of the SDK.

Updating the context on the client side re-establishes a new connection to ConfigDirector servers with the new context. While the new connection is in flight, config values will continue to evaluate to the currently cached values from the prior context.Give the provider the context you know when the page loads, so the first connection carries it. A context set only afterwards replaces a first connection that had none, and that first connection counts as a separate monthly active user. If your application learns its context only after an asynchronous step in the browser, turn on deferInitialization so that the browser waits for the first updateContext call and its first connection already carries the context.

In the browser, the SDK keeps an instance ID in localStorage until the site's data is cleared, and ConfigDirector derives the identifier of a context without an id from it. A visitor who has not signed in keeps that identifier, and their percentage rollout bucket, from one visit to the next, and counts as one monthly active user however often they visit.

Test your code

The SDK ships two testing entry points. @configdirector/nextjs-sdk/client/testing is for Client Components that read your configs and flags, and @configdirector/nextjs-sdk/server/testing is for server code that uses getConfigClient(), generateSsrConfigSet(), or the server ConfigDirectorProvider. Each creates a test client: the SDK's real client connected to an in-memory server that your test controls. Only the connection to ConfigDirector is replaced. Everything else is the same code that runs in production, so the code under test behaves exactly as it does against ConfigDirector, and no network connection is opened and no telemetry is sent.

Client Components

Render the production client ConfigDirectorProvider with its client prop:

Checkout.test.tsx
import { act, render, screen } from "@testing-library/react";
import { ConfigDirectorProvider } from "@configdirector/nextjs-sdk/client";
import { createTestClient } from "@configdirector/nextjs-sdk/client/testing";
import { Checkout } from "./Checkout";

test("shows the new checkout when the flag is on", async () => {
  const testClient = createTestClient({ values: { "new-checkout": true } });

  render(
    <ConfigDirectorProvider client={testClient.client}>
      <Checkout />
    </ConfigDirectorProvider>,
  );

  expect(await screen.findByText("New checkout")).toBeInTheDocument();

  act(() => testClient.setValue("new-checkout", false));
  expect(screen.getByText("Classic checkout")).toBeInTheDocument();
});

Until the client is ready, the hooks show initialConfigs when the provider was given them, or the in-code default value, so the first assertion uses findBy… rather than getBy…; a test client whose client was initialized before rendering is ready on the first render. Wrap setValue, removeValue, and replaceValues in act().

For a component that renders the client provider itself with an sdkKey, installTestClient makes every provider mounted without a client prop use the test client instead, until the returned function uninstalls it:

App.test.tsx
import { createTestClient, installTestClient } from "@configdirector/nextjs-sdk/client/testing";

let uninstallTestClient: () => void;

beforeEach(() => {
  uninstallTestClient = installTestClient(createTestClient({ values: { "new-checkout": true } }));
});
afterEach(() => uninstallTestClient());

While installed, the provider's construction props (sdkKey, url, mode, timeout, pollingInterval, logLevel, appName, appVersion) are ignored; context, hooks, and initialConfigs apply as they do with a client prop. A provider given a client never disposes it, removes its handlers when it unmounts, does not call initialize on a client that is ready or initializing, updates the context only when the context prop is given and differs from the client's context, compares contexts by deep equality, and ignores a client prop that changes after mount with a warning. With deferInitialization on, it leaves a client that is neither ready nor initializing untouched until the first context, from the prop or from updateContext, initializes it.

Server code

Server code reads the singleton that register() creates in instrumentation.ts through getConfigClient(). register() never runs in unit tests, so installServerTestClient puts a server test client's client in its place and returns a function that restores the previous one. It does not initialize the client; the test does, as register() would:

flags.test.ts
import { getConfigClient } from "@configdirector/nextjs-sdk/server";
import { createTestClient, installServerTestClient } from "@configdirector/nextjs-sdk/server/testing";

let uninstallServerTestClient: () => void;

beforeEach(async () => {
  const testClient = createTestClient({ values: { "new-checkout": true } });
  uninstallServerTestClient = installServerTestClient(testClient);
  await testClient.client.initialize();
});
afterEach(() => uninstallServerTestClient());

test("serves the flag to every user", () => {
  expect(getConfigClient().getValue("new-checkout", false, { id: "user-1" })).toBe(true);
});

generateSsrConfigSet() and the server ConfigDirectorProvider then serve the test client's values. The server provider is an async Server Component, which React Testing Library cannot render; call it as an async function and assert on the initialConfigs prop of the element it returns. Every value is served as an unconditional config, so every context receives the same value.

Test client controls

values, setValue, removeValue, and replaceValues take native values, and the config type follows from each value: a boolean, an integral number (integer), any other number (float), a string, or a plain object or array (json). holdInitialization, completeInitialization, and failInitialization drive initialize; the client test client also holds, completes, or fails updateContext and records every context in contextUpdates. Both test clients record the events the code under test tracked with track in trackedEvents. The JavaScript SDK's testing section and the Node.js SDK's testing section describe every control and what to expect from each client.