Next.js (App Router) quickstart

1. Install hypertune

Once you have a Next.js application (using the App Router) ready, install the hypertune and server-only packages:

npm install hypertune server-only

2. Set environment variables

Define the following environment variables in your .env file:

.env
NEXT_PUBLIC_HYPERTUNE_TOKEN=token
HYPERTUNE_FRAMEWORK=nextApp
HYPERTUNE_OUTPUT_DIRECTORY_PATH=generated

Replace token with your main project token which you can find in the Settings tab of your project.

3. Generate the client

Generate a type-safe client to access your flags by running:

npx hypertune

4. Use the client

Add a new file called getHypertune.ts that exports a getHypertune function:

lib/getHypertune.ts
import "server-only";
import { unstable_noStore as noStore } from "next/cache";
import { createSource } from "@/generated/hypertune";

const hypertuneSource = createSource({
  token: process.env.NEXT_PUBLIC_HYPERTUNE_TOKEN!,
});

export default async function getHypertune() {
  noStore();
  await hypertuneSource.initIfNeeded(); // Check for flag updates

  return hypertuneSource.root({
    args: {
      context: {
        environment: process.env.NODE_ENV,
        user: { id: "1", name: "Test", email: "[email protected]" },
      },
    },
  });
}

To access flags in React Server Components (RSC), use the getHypertune function:

components/ServerComponent.tsx
import getHypertune from "@/lib/getHypertune";

export default async function ServerComponent() {
  const hypertune = await getHypertune();

  const exampleFlag = hypertune.exampleFlag({ fallback: false });

  return <div>Example Flag: {String(exampleFlag)}</div>;
}

5. (Optional) Include a build-time logic snapshot

To improve reliability, you can include a snapshot of your flag logic in the generated client at build time. The SDK will instantly initialize from the snapshot first before fetching the latest flag logic from Hypertune Edge.

Add the following environment variable to your .env file:

.env
HYPERTUNE_INCLUDE_INIT_DATA=true

Then run npx hypertune to regenerate the client.

You can keep the snapshot fresh by setting up a webhook to regenerate the client on every Hypertune commit. In this case, you don't need to initialize from Hypertune Edge at all, eliminating network latency and bandwidth, improving both performance and efficiency.

6. (Optional) Use Vercel Edge Config

If your Next.js app is deployed on Vercel, you can use Edge Config to initialize the Hypertune SDK on the server with near-zero latency.

1. Install the integration

  1. Go to the Hypertune page in the Vercel Integrations marketplace and click "Add Integration".

  2. Select your Vercel team and project.

  3. Continue and log into Hypertune.

  4. Connect your Hypertune project to a new or existing Edge Config store. Copy the displayed environment variables for later. They contain your Hypertune Token, Edge Config Connection String, and Edge Config Item Key.

  5. Go to your Vercel dashboard and select the project you want to use the Hypertune integration with. Go to Settings > Environment Variables and add the following:

    1. NEXT_PUBLIC_HYPERTUNE_TOKEN, set to your Hypertune Token

    2. EDGE_CONFIG, set to your Edge Config Connection String

    3. EDGE_CONFIG_HYPERTUNE_ITEM_KEY, set to your Edge Config Item Key

2. Use the integration

Pull the environment variables to your .env.development.local file by running:

vercel env pull .env.development.local

Install the @vercel/edge-config package:

npm install @vercel/edge-config

Finally, update your getHypertune function to create an Edge Config client and pass it along with your Edge Config Item Key when creating the Hypertune source:

lib/getHypertune.ts
import "server-only";
import { VercelEdgeConfigInitDataProvider } from "hypertune";
import { unstable_noStore as noStore } from "next/cache";
import { createClient } from "@vercel/edge-config";
import { createSource } from "@/generated/hypertune";

const hypertuneSource = createSource({
  token: process.env.NEXT_PUBLIC_HYPERTUNE_TOKEN!,
  initDataProvider:
    process.env.EDGE_CONFIG &&
    process.env.EDGE_CONFIG_HYPERTUNE_ITEM_KEY
      ? new VercelEdgeConfigInitDataProvider({
          edgeConfigClient: createClient(
            process.env.EDGE_CONFIG,
          ),
          itemKey: process.env.EDGE_CONFIG_HYPERTUNE_ITEM_KEY,
        })
      : undefined,
});

export default async function getHypertune() {
  noStore();
  await hypertuneSource.initIfNeeded(); // Check for flag updates

  return hypertuneSource.root({
    args: {
      context: {
        environment: process.env.NODE_ENV,
        user: { id: "1", name: "Test", email: "[email protected]" },
      },
    },
  });
}

7. (Optional) Integrate with the Vercel Toolbar and Flags Explorer

1. Set up the Vercel Toolbar

Follow the guide to add the Vercel Toolbar to your local environment.

2. Generate a FLAGS_SECRET environment variable

Open the Flags Explorer from the Toolbar and follow the prompts to generate a FLAGS_SECRET environment variable and pull it locally with vercel env pull.

3. Provide flag definitions to the Vercel Toolbar

Install the flags package:

npm install flags

Then add a new route handler in app/.well-known/vercel/flags/route.ts to provide flag definitions to the Vercel Toolbar using the generated vercelFlagDefinitions constant:

app/.well-known/vercel/flags/route.ts
import { createFlagsDiscoveryEndpoint } from 'flags/next'
import { vercelFlagDefinitions } from '../../../../generated/hypertune'

export const GET = createFlagsDiscoveryEndpoint(() => {
  return { definitions: vercelFlagDefinitions }
})

4. Generate Vercel integration helpers

Add the following environment variable to your .env file:

.env
HYPERTUNE_PLATFORM=vercel

Then run npx hypertune to regenerate the client.

5. Respect flag overrides set by the Vercel Toolbar

Update your getHypertune function to respect flag overrides set by the Vercel Toolbar using the generated getVercelOverride function:

lib/getHypertune.ts
import "server-only";
import { unstable_noStore as noStore } from "next/cache";
import { createSource } from "@/generated/hypertune";
import { getVercelOverride } from "@/generated/hypertune.vercel";

const hypertuneSource = createSource({
  token: process.env.NEXT_PUBLIC_HYPERTUNE_TOKEN!,
});

export default async function getHypertune() {
  noStore();
  await hypertuneSource.initIfNeeded(); // Check for flag updates

  // Respect flag overrides set by the Vercel Toolbar
  hypertuneSource.setOverride(await getVercelOverride());

  return hypertuneSource.root({
    args: {
      context: {
        environment: process.env.NODE_ENV,
        user: { id: "1", name: "Test", email: "[email protected]" },
      },
    },
  });
}

6. Provide flag values to the Vercel Toolbar

Add the generated <VercelFlagValues> component to your app to tell the Vercel Toolbar about your flag values:

components/ServerComponent.tsx
import { VercelFlagValues } from "@/generated/hypertune.vercel";
import getHypertune from "@/lib/getHypertune";

export default async function ServerComponent() {
  const hypertune = await getHypertune();

  const exampleFlag = hypertune.exampleFlag({ fallback: false });

  return (
    <div>
      Example Flag: {String(exampleFlag)}
      <VercelFlagValues flagValues={hypertune.get()} />
    </div>
  );
}

8. (Optional) Integrate with Vercel's Flags SDK

You can integrate Hypertune with Vercel's Flags SDK to use Vercel's Flags pattern on the server, e.g. in Server Components, Route Handlers, or Middleware.

Install the required dependencies:

npm install flags @flags-sdk/hypertune @vercel/edge-config

Create a new file called flags.ts that contains an identify function and a hypertuneAdapter, and defines your flag functions:

flags.ts
import { Identify } from "flags";
import { dedupe, flag } from "flags/next";
import { createHypertuneAdapter } from "@flags-sdk/hypertune";
import {
  createSource,
  flagFallbacks,
  vercelFlagDefinitions as flagDefinitions,
  Context,
  RootFlagValues,
} from "./generated/hypertune";

const identify: Identify<Context> = dedupe(
  async ({ headers, cookies }) => {
    return {
      environment: process.env.NODE_ENV,
      user: { id: "1", name: "Test User", email: "[email protected]" },
    };
  },
);

const hypertuneAdapter = createHypertuneAdapter<
  RootFlagValues,
  Context
>({
  createSource,
  flagFallbacks,
  flagDefinitions,
  identify,
});

export const exampleFlagFlag = flag(
  hypertuneAdapter.declarations.exampleFlag,
);

export const enableDesignV2Flag = flag(
  hypertuneAdapter.declarations.enableDesignV2,
);

To use flags, import and await your flag functions:

components/ServerComponent.tsx
import { exampleFlagFlag } from "@/flags";

export default async function ServerComponent() {
  const exampleFlag = await exampleFlagFlag();

  return <div>Example Flag: {String(exampleFlag)}</div>;
}

To use the Flags Explorer in the Vercel Toolbar, add a new route handler in app/.well-known/vercel/flags/route.ts to provide flag definitions to it using the generated vercelFlagDefinitions constant:

app/.well-known/vercel/flags/route.ts
import { createFlagsDiscoveryEndpoint } from 'flags/next'
import { vercelFlagDefinitions } from '../../../../generated/hypertune'

export const GET = createFlagsDiscoveryEndpoint(() => {
  return { definitions: vercelFlagDefinitions }
})

To use Vercel Edge Config with the Flags SDK, configure it via environment variables:

.env
EXPERIMENTATION_CONFIG="https://edge-config.vercel.com/ecfg_xyz?token=abc"
EXPERIMENTATION_CONFIG_ITEM_KEY="hypertune_99999"

Or via the adapter:

flags.ts
import { Identify } from "flags";
import { dedupe, flag } from "flags/next";
import { createHypertuneAdapter } from "@flags-sdk/hypertune";
import { VercelEdgeConfigInitDataProvider } from "hypertune";
import { createClient } from "@vercel/edge-config";
import {
  createSource,
  flagFallbacks,
  vercelFlagDefinitions as flagDefinitions,
  Context,
  RootFlagValues,
} from "./generated/hypertune";

const identify: Identify<Context> = dedupe(
  async ({ headers, cookies }) => {
    return {
      environment: process.env.NODE_ENV,
      user: { id: "1", name: "Test User", email: "[email protected]" },
    };
  },
);

const hypertuneAdapter = createHypertuneAdapter<
  RootFlagValues,
  Context
>({
  createSource,
  flagFallbacks,
  flagDefinitions,
  identify,
  initDataProvider: new VercelEdgeConfigInitDataProvider({
    edgeConfigClient: createClient(
      "https://edge-config.vercel.com/ecfg_xyz?token=abc",
    ),
    itemKey: "hypertune_99999",
  }),
});

export const exampleFlagFlag = flag(
  hypertuneAdapter.declarations.exampleFlag,
);

export const enableDesignV2Flag = flag(
  hypertuneAdapter.declarations.enableDesignV2,
);

That's it

Now you can update the logic for exampleFlag from the Hypertune UI without updating your code or waiting for a new build, deployment, or app release.

To add a new flag, create it in the Hypertune UI then regenerate the client.

Last updated