# 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:

{% tabs %}
{% tab title="npm" %}

```bash
npm install hypertune server-only
```

{% endtab %}

{% tab title="yarn" %}

```bash
yarn add hypertune server-only
```

{% endtab %}

{% tab title="pnpm" %}

```bash
pnpm add hypertune server-only
```

{% endtab %}
{% endtabs %}

## 2. Set environment variables

Set the following environment variables in your `.env` file:

{% code title=".env" %}

```bash
NEXT_PUBLIC_HYPERTUNE_TOKEN=token
HYPERTUNE_FRAMEWORK=nextApp
HYPERTUNE_OUTPUT_DIRECTORY_PATH=generated
```

{% endcode %}

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:

{% tabs %}
{% tab title="npm" %}

```bash
npx hypertune
```

{% endtab %}

{% tab title="yarn" %}

```bash
yarn hypertune
```

{% endtab %}

{% tab title="pnpm" %}

```bash
pnpm hypertune
```

{% endtab %}
{% endtabs %}

## 4. Use the client

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

{% code title="lib/getHypertune.ts" %}

```typescript
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({
  isRouteHandler = false,
}: {
  isRouteHandler?: boolean
} = {}) {
  noStore()

  await hypertuneSource.initIfNeeded()

  hypertuneSource.setRemoteLoggingMode(
    isRouteHandler ? 'normal' : 'off'
  )

  return hypertuneSource.root({
    args: {
      context: {
        environment: process.env.NODE_ENV,
        user: {
          id: 'e23cc9a8-0287-40aa-8500-6802df91e56a',
          name: 'Example User',
          email: 'user@example.com',
        },
      },
    },
  })
}
```

{% endcode %}

{% tabs %}
{% tab title="Client Components" %}
To use flags in Client Components, first wrap your app with the generated `<HypertuneProvider>` component in your root layout:

{% code title="app/layout.tsx" %}

```tsx
import { HypertuneProvider } from '@/generated/hypertune.react'
import getHypertune from '@/lib/getHypertune'
import './globals.css'

export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode
}>) {
  const hypertune = await getHypertune()
  
  const dehydratedState = hypertune.dehydrate()
  const rootArgs = hypertune.getRootArgs()

  return (
    <HypertuneProvider
      createSourceOptions={{
        token: process.env.NEXT_PUBLIC_HYPERTUNE_TOKEN!,
      }}
      dehydratedState={dehydratedState}
      rootArgs={rootArgs}
    >
      <html lang="en">
        <body>{children}</body>
      </html>
    </HypertuneProvider>
  )
}
```

{% endcode %}

Then use the generated `useHypertune` hook:

{% code title="components/ClientComponent.tsx" %}

```tsx
'use client'

import { useHypertune } from '@/generated/hypertune.react'

export default function ClientComponent() {
  const hypertune = useHypertune()

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

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

{% endcode %}

**Notes**

* **Dynamic rendering:** Calling `getHypertune` in your root layout makes your entire app dynamic. To keep parts of your app static (e.g. marketing pages), see **(Static) Client Components**.
* **Hydration:** Passing `dehydratedState` from the server instantly hydrates the SDK in the browser. This ensures you can use flags on the first render with no layout shift, flicker, or delay. If omitted, the SDK will initialize in the background and trigger a re-render once ready.
* **Root args:** Passing `rootArgs` from the server lets you reuse the root args from `getHypertune` on the server. This is optional — you can also construct root args on the client.
* **Content Security Policy:** If you use a CSP, add the following to your `connect-src` directive: `https://edge.hypertune.com https://gcp.fasthorse.workers.dev`. This enables reporting of flag evaluations, experiment exposures, and analytics events.
  {% endtab %}

{% tab title="(Static) Client Components" %}
To use flags in Client Components while keeping parts of your app static (e.g. marketing pages), first create a new `<AppHypertuneProvider>` component that wraps the generated `<HypertuneProvider>` component:

{% code title="components/AppHypertuneProvider.tsx" %}

```tsx
'use client'

import { HypertuneProvider } from '@/generated/hypertune.react'

export default function AppHypertuneProvider({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <HypertuneProvider
      createSourceOptions={{
        token: process.env.NEXT_PUBLIC_HYPERTUNE_TOKEN!,
      }}
      rootArgs={{
        context: {
          environment: process.env.NODE_ENV,
          user: {
            id: 'e23cc9a8-0287-40aa-8500-6802df91e56a',
            name: 'Example User',
            email: 'user@example.com',
          },
        },
      }}
    >
      {children}
    </HypertuneProvider>
  )
}
```

{% endcode %}

Wrap your app with the `<AppHypertuneProvider>` component in your root layout:

{% code title="app/layout.tsx" %}

```tsx
import AppHypertuneProvider from '@/components/AppHypertuneProvider'
import './globals.css'

export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode
}>) {
  return (
    <AppHypertuneProvider>
      <html lang="en">
        <body>{children}</body>
      </html>
    </AppHypertuneProvider>
  )
}
```

{% endcode %}

Then use the generated `useHypertune` hook:

{% code title="components/ClientComponent.tsx" %}

```tsx
'use client'

import { useHypertune } from '@/generated/hypertune.react'

export default function ClientComponent() {
  const hypertune = useHypertune()

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

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

{% endcode %}

If you access a flag immediately after your app loads, you'll get your hardcoded fallback value if the SDK hasn't initialized from [Hypertune Edge](https://docs.hypertune.com/concepts/hypertune-edge) yet. This can result in layout shift or a flicker if the flag value changes when the SDK initializes.

To avoid this, wrap your page with the generated `<HypertuneHydrator>` and `<HypertuneRootProvider>` components, passing them `dehydratedState` and `rootArgs` from the server:

{% code title="app/page.tsx" %}

```tsx
import React from 'react'
import ClientComponent from '@/components/ClientComponent'
import ServerComponent from '@/components/ServerComponent'
import {
  HypertuneHydrator,
  HypertuneRootProvider,
} from '@/generated/hypertune.react'
import getHypertune from '@/lib/getHypertune'

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

  const dehydratedState = hypertune.dehydrate()
  const rootArgs = hypertune.getRootArgs()

  return (
    <HypertuneHydrator dehydratedState={dehydratedState}>
      <HypertuneRootProvider rootArgs={rootArgs}>
        <ServerComponent />
        <ClientComponent />
      </HypertuneRootProvider>
    </HypertuneHydrator>
  )
}
```

{% endcode %}

**Notes**

* **Dynamic rendering:** Calling `getHypertune` makes your entire page dynamic. To use flags and run experiments on static pages (e.g. marketing pages), see the guide on [using Hypertune on static pages](https://docs.hypertune.com/guides/use-hypertune-on-static-pages).
* **Content Security Policy:** If you have a CSP, add the following to your `connect-src` directive: `https://edge.hypertune.com https://gcp.fasthorse.workers.dev`. This enables reporting of flag evaluations, experiment exposures, and analytics events.
  {% endtab %}

{% tab title="Server Components" %}
To use flags in Server Components, use the `getHypertune` function. Include the `<HypertuneClientLogger>` component in your component tree, passing it the paths of any flags you use via the `flagPaths` prop. This ensures that flag evaluations and experiment exposures are logged on the client (in the browser):

{% code title="components/ServerComponent.tsx" %}

```tsx
import { HypertuneClientLogger } from '@/generated/hypertune.react'
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)}
      <HypertuneClientLogger flagPaths={['exampleFlag']} />
    </div>
  )
}
```

{% endcode %}

By default, [remote logging](https://docs.hypertune.com/sdk-reference/remote-logging) is disabled on Next.js servers because prefetching and caching of pages and layouts can cause logs for flag evaluations, experiment exposures, and analytics events to differ from actual user behaviour. To ensure accuracy, remote logging is enabled by default on the client (in the browser) only. This is why you need to include the `<HypertuneClientLogger>` component in your component tree.
{% endtab %}

{% tab title="Route Handlers" %}
To use flags in Route Handlers, use the `getHypertune` function:

{% code title="app/api/route.ts" %}

```typescript
import { waitUntil } from '@vercel/functions'
import { NextResponse } from 'next/server'
import getHypertune from '@/lib/getHypertune'

export const runtime = 'edge'

export async function GET() {
  const hypertune = await getHypertune({ isRouteHandler: true })

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

  waitUntil(hypertune.flushLogs())

  return NextResponse.json({ exampleFlag })
}
```

{% endcode %}

**Notes**

* **Enable remote logging:** By default, [remote logging](https://docs.hypertune.com/sdk-reference/remote-logging) is disabled on Next.js servers because prefetching and caching of pages and layouts can cause logs for flag evaluations, experiment exposures, and analytics events to differ from actual user behaviour. To ensure accuracy, remote logging is enabled by default on the client (in the browser) only. However, since Route Handlers aren't subject to the same prefetching and caching patterns, remote logging is enabled for them by passing `{ isRouteHandler: true }` in the call to `getHypertune`.
* **Flush logs:** `waitUntil(hypertune.flushLogs())` ensures that logs are sent. Without this, logs may still flush in the background, but this isn't guaranteed in serverless environments like Vercel deployments.
  {% endtab %}

{% tab title="Middleware" %}
To use flags in Middleware, use the `getHypertune` function:

{% code title="middleware.ts" %}

```typescript
import { NextRequest } from 'next/server'
import getHypertune from '@/lib/getHypertune'

export const config = {
  matcher: '/:path*',
}

export async function middleware(request: NextRequest) {
  const hypertune = await getHypertune()

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

  console.log(`Example Flag: ${exampleFlag}`)
}
```

{% endcode %}

Include the `<HypertuneClientLogger>` component in your component tree, passing it the paths of any flags you use via the `flagPaths` prop. This ensures that flag evaluations and experiment exposures are logged on the client (in the browser):

{% code title="app/page.tsx" %}

```typescript
import React from 'react'
import { HypertuneClientLogger } from '@/generated/hypertune.react'

export default async function Home() {
  return (
    <div>
      <h1>Home</h1>
      <HypertuneClientLogger flagPaths={['exampleFlag']} />
    </div>
  )
}
```

{% endcode %}

By default, [remote logging](https://docs.hypertune.com/sdk-reference/remote-logging) is disabled on Next.js servers because prefetching and caching of pages and layouts can cause logs for flag evaluations, experiment exposures, and analytics events to differ from actual user behaviour. To ensure accuracy, remote logging is enabled by default on the client (in the browser) only. This is why you need to include the `<HypertuneClientLogger>` component in your component tree.
{% endtab %}
{% endtabs %}

## 5. (Optional) Add the Hypertune Toolbar

The Hypertune Toolbar lets you view and override feature flags directly in your frontend. [Follow the guide](https://docs.hypertune.com/sdk-reference/hypertune-toolbar) to add it to your app.

## 6. (Optional) Include a build-time 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](https://docs.hypertune.com/concepts/hypertune-edge).

Add the following environment variable to your `.env` file:

{% code title=".env" %}

```bash
HYPERTUNE_INCLUDE_INIT_DATA=true
```

{% endcode %}

Then run `npx hypertune` to regenerate the client.

You can keep the snapshot fresh by setting up a [webhook](https://docs.hypertune.com/integrations/webhooks) 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.

## 7. (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](https://vercel.com/integrations/hypertune) 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:

{% tabs %}
{% tab title="npm" %}

```bash
npm install @vercel/edge-config
```

{% endtab %}

{% tab title="yarn" %}

```bash
yarn add @vercel/edge-config
```

{% endtab %}

{% tab title="pnpm" %}

```bash
pnpm add @vercel/edge-config
```

{% endtab %}
{% endtabs %}

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:

{% code title="lib/getHypertune.ts" %}

```typescript
import 'server-only'
import { createClient } from '@vercel/edge-config'
import { VercelEdgeConfigInitDataProvider } from 'hypertune'
import { unstable_noStore as noStore } from 'next/cache'
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({
  isRouteHandler = false,
}: {
  isRouteHandler?: boolean
} = {}) {
  noStore()

  await hypertuneSource.initIfNeeded()

  hypertuneSource.setRemoteLoggingMode(
    isRouteHandler ? 'normal' : 'off'
  )

  return hypertuneSource.root({
    args: {
      context: {
        environment: process.env.NODE_ENV,
        user: {
          id: 'e23cc9a8-0287-40aa-8500-6802df91e56a',
          name: 'Example User',
          email: 'user@example.com',
        },
      },
    },
  })
}
```

{% endcode %}

## 8. (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](https://vercel.com/docs/vercel-toolbar/in-production-and-localhost/add-to-localhost).

### 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:

{% tabs %}
{% tab title="npm" %}

```bash
npm install flags
```

{% endtab %}

{% tab title="yarn" %}

```bash
yarn add flags
```

{% endtab %}

{% tab title="pnpm" %}

```bash
pnpm add flags
```

{% endtab %}
{% endtabs %}

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:

{% code title="app/.well-known/vercel/flags/route.ts" %}

```typescript
import { createFlagsDiscoveryEndpoint } from 'flags/next'
import { vercelFlagDefinitions } from '../../../../generated/hypertune'

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

{% endcode %}

### 4. Generate Vercel integration helpers

Add the following environment variable to your `.env` file:

{% code title=".env" %}

```bash
HYPERTUNE_PLATFORM=vercel
```

{% endcode %}

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:

{% code title="lib/getHypertune.ts" %}

```typescript
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: 'e23cc9a8-0287-40aa-8500-6802df91e56a',
          name: 'Example User',
          email: 'user@example.com',
        },
      },
    },
  })
}
```

{% endcode %}

### 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:

{% code title="components/ServerComponent.tsx" %}

```typescript
import { HypertuneProvider } from '@/generated/hypertune.react'
import { VercelFlagValues } from '@/generated/hypertune.vercel'
import getHypertune from '@/lib/getHypertune'
import './globals.css'

export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode
}>) {
  const hypertune = await getHypertune()

  const serverDehydratedState = hypertune.dehydrate()
  const serverRootArgs = hypertune.getRootArgs()

  return (
    <HypertuneProvider
      createSourceOptions={{
        token: process.env.NEXT_PUBLIC_HYPERTUNE_TOKEN!,
      }}
      dehydratedState={serverDehydratedState}
      rootArgs={serverRootArgs}
    >
      <html lang="en">
        <body>
          {children}
          <VercelFlagValues flagValues={hypertune.get()} />
        </body>
      </html>
    </HypertuneProvider>
  )
}
```

{% endcode %}

## 9. (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:

{% tabs %}
{% tab title="npm" %}

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

{% endtab %}

{% tab title="yarn" %}

```bash
yarn add flags @flags-sdk/hypertune @vercel/edge-config
```

{% endtab %}

{% tab title="pnpm" %}

```bash
pnpm add flags @flags-sdk/hypertune @vercel/edge-config
```

{% endtab %}
{% endtabs %}

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

{% code title="flags.ts" %}

```typescript
import { createHypertuneAdapter } from '@flags-sdk/hypertune'
import { Identify } from 'flags'
import { dedupe, flag } from 'flags/next'
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: 'e23cc9a8-0287-40aa-8500-6802df91e56a',
        name: 'Example User',
        email: 'user@example.com',
      },
    }
  }
)

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

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

export const enableDesignV2Flag = flag(
  hypertuneAdapter.declarations.enableDesignV2
)
```

{% endcode %}

To use flags, import and await your flag functions:

{% code title="components/ServerComponent.tsx" %}

```typescript
import { exampleFlagFlag } from '@/flags'

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

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

{% endcode %}

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:

{% code title="app/.well-known/vercel/flags/route.ts" %}

```typescript
import { createFlagsDiscoveryEndpoint } from 'flags/next'
import { vercelFlagDefinitions } from '../../../../generated/hypertune'

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

{% endcode %}

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

{% code title=".env" %}

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

{% endcode %}

Or via the adapter:

{% code title="flags.ts" %}

```typescript
import { createHypertuneAdapter } from '@flags-sdk/hypertune'
import { createClient } from '@vercel/edge-config'
import { Identify } from 'flags'
import { dedupe, flag } from 'flags/next'
import { VercelEdgeConfigInitDataProvider } from '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: 'e23cc9a8-0287-40aa-8500-6802df91e56a',
        name: 'Example User',
        email: 'user@example.com',
      },
    }
  }
)

const hypertuneAdapter = createHypertuneAdapter<
  RootFlagValues,
  Context
>({
  createSource,
  flagFallbacks,
  flagDefinitions,
  identify,
  createSourceOptions: {
    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
)
```

{% endcode %}

## Next steps

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.
