# Next.js (Pages Router) quickstart

## 1. Install `hypertune`

Once you have a Next.js application (using the Pages Router) ready, install Hypertune's JavaScript SDK:

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

```bash
npm install hypertune
```

{% endtab %}

{% tab title="yarn" %}

```bash
yarn add hypertune
```

{% endtab %}

{% tab title="pnpm" %}

```bash
pnpm add hypertune
```

{% endtab %}
{% endtabs %}

## 2. Set environment variables

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

{% code title=".env" %}

```bash
NEXT_PUBLIC_HYPERTUNE_TOKEN=token
HYPERTUNE_FRAMEWORK=nextPages
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 { createSourceForServerOnly } from '@/generated/hypertune'

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

export default async function getHypertune({
  isApiRoute = false,
}: {
  isApiRoute?: boolean
} = {}) {
  await hypertuneSource.initIfNeeded()

  hypertuneSource.setRemoteLoggingMode(
    isApiRoute ? '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="Components" %}
To use flags in components, first create a new `<AppHypertuneProvider>` component that wraps the generated `<HypertuneProvider>` component:

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

```tsx
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 `_app.tsx`:

{% code title="pages/\_app.tsx" %}

```tsx
import type { AppProps } from 'next/app'
import AppHypertuneProvider from '@/components/AppHypertuneProvider'
import '@/styles/globals.css'

export default function App({ Component, pageProps }: AppProps) {
  return (
    <AppHypertuneProvider>
      <Component {...pageProps} />
    </AppHypertuneProvider>
  )
}
```

{% endcode %}

Then use the generated `useHypertune` hook:

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

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

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

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

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

{% endcode %}

If you access a flag immediately after the app loads, you'll get your hardcoded fallback value if the SDK hasn't initialized from [Hypertune Edge](/concepts/hypertune-edge.md) 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="pages/index.tsx" %}

```tsx
import {
  GetServerSideProps,
  InferGetServerSidePropsType,
} from 'next'
import ExampleComponent from '@/components/ExampleComponent'
import { DehydratedState, RootArgs } from '@/generated/hypertune'
import {
  HypertuneHydrator,
  HypertuneRootProvider,
} from '@/generated/hypertune.react'
import getHypertune from '@/lib/getHypertune'

type Props = {
  dehydratedState: DehydratedState | null
  rootArgs: RootArgs
}

export const getServerSideProps = (async () => {
  const hypertune = await getHypertune()

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

  return { props: { dehydratedState, rootArgs } }
}) satisfies GetServerSideProps<Props>

export default function Page({
  dehydratedState,
  rootArgs,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
  return (
    <HypertuneHydrator dehydratedState={dehydratedState}>
      <HypertuneRootProvider rootArgs={rootArgs}>
        <ExampleComponent />
      </HypertuneRootProvider>
    </HypertuneHydrator>
  )
}
```

{% endcode %}

**Notes**

* **Dynamic rendering**: Using `getServerSideProps` 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](/guides/use-hypertune-on-static-pages.md).
* **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="getServerSideProps" %}
To use flags in `getServerSideProps`, 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="pages/index.tsx" %}

```tsx
import {
  GetServerSideProps,
  InferGetServerSidePropsType,
} from 'next'
import { DehydratedState, RootArgs } from '@/generated/hypertune'
import {
  HypertuneClientLogger,
  HypertuneHydrator,
  HypertuneRootProvider,
} from '@/generated/hypertune.react'
import getHypertune from '@/lib/getHypertune'

type Props = {
  dehydratedState: DehydratedState | null
  rootArgs: RootArgs
  exampleFlag: boolean
}

export const getServerSideProps = (async () => {
  const hypertune = await getHypertune()

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

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

  return { props: { dehydratedState, rootArgs, exampleFlag } }
}) satisfies GetServerSideProps<Props>

export default function Page({
  dehydratedState,
  rootArgs,
  exampleFlag,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
  return (
    <HypertuneHydrator dehydratedState={dehydratedState}>
      <HypertuneRootProvider rootArgs={rootArgs}>
        <div>
          Example Flag: {exampleFlag}
          <HypertuneClientLogger flagPaths={['exampleFlag']} />
        </div>
      </HypertuneRootProvider>
    </HypertuneHydrator>
  )
}
```

{% endcode %}

By default, [remote logging](/sdk-reference/remote-logging.md) 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="API Routes" %}
To use flags in API Routes, use the `getHypertune` function:

{% code title="pages/api/example.ts" %}

```typescript
import { waitUntil } from '@vercel/functions'
import type { NextApiRequest, NextApiResponse } from 'next'
import getHypertune from '@/lib/getHypertune'

type ResponseData = { exampleFlag: boolean }

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<ResponseData>
) {
  const hypertune = await getHypertune({ isApiRoute: true })

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

  waitUntil(hypertune.flushLogs())

  res.status(200).json({ exampleFlag })
}
```

{% endcode %}

**Notes**

* **Enable remote logging:** By default, [remote logging](/sdk-reference/remote-logging.md) 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 API Routes aren't subject to the same prefetching and caching patterns, remote logging is enabled for them by passing `{ isApiRoute: 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: '/(.*)',
}

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="pages/index.tsx" %}

```typescript
import {
  GetServerSideProps,
  InferGetServerSidePropsType,
} from 'next'
import { DehydratedState, RootArgs } from '@/generated/hypertune'
import {
  HypertuneClientLogger,
  HypertuneHydrator,
  HypertuneRootProvider,
} from '@/generated/hypertune.react'
import getHypertune from '@/lib/getHypertune'

type Props = {
  dehydratedState: DehydratedState | null
  rootArgs: RootArgs
}

export const getServerSideProps = (async () => {
  const hypertune = await getHypertune()

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

  return { props: { dehydratedState, rootArgs } }
}) satisfies GetServerSideProps<Props>

export default function Page({
  dehydratedState,
  rootArgs,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
  return (
    <HypertuneHydrator dehydratedState={dehydratedState}>
      <HypertuneRootProvider rootArgs={rootArgs}>
        <div>
          <h1>Home</h1>
          <HypertuneClientLogger flagPaths={['exampleFlag']} />
        </div>
      </HypertuneRootProvider>
    </HypertuneHydrator>
  )
}
```

{% endcode %}

By default, [remote logging](/sdk-reference/remote-logging.md) 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](/sdk-reference/hypertune-toolbar.md) 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](/concepts/hypertune-edge.md).

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

```bash
HYPERTUNE_INCLUDE_INIT_DATA=true
```

Then regenerate the client.

You can keep the snapshot fresh by setting up a [webhook](/integrations/webhooks.md) 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 { createClient } from '@vercel/edge-config'
import { VercelEdgeConfigInitDataProvider } from 'hypertune'
import { createSourceForServerOnly } from '@/generated/hypertune'

const hypertuneSource = createSourceForServerOnly({
  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({
  isApiRoute = false,
}: {
  isApiRoute?: boolean
} = {}) {
  await hypertuneSource.initIfNeeded()

  hypertuneSource.setRemoteLoggingMode(
    isApiRoute ? '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 %}

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.hypertune.com/getting-started/next.js-pages-router-quickstart.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
