Hypertune
  • Introduction
  • Getting Started
    • Set up Hypertune
    • Next.js (App Router) quickstart
    • Next.js (Pages Router) quickstart
    • React quickstart
    • Remix quickstart
    • Gatsby quickstart
    • Vue quickstart
    • Nuxt quickstart
    • Node.js quickstart
    • React Native quickstart
    • JavaScript quickstart
    • Python quickstart
    • Rust quickstart
    • Go quickstart
    • Web quickstart
    • GraphQL quickstart
  • Example apps
    • Next.js and Vercel example app
  • Concepts
    • Architecture
    • Project
    • Schema
    • Flag lifecycle
    • Logic
    • Variables
    • Splits
    • A/B tests
    • Staged rollouts
    • Multivariate tests
    • Machine learning loops
    • Events
    • Funnels
    • Hypertune Edge
    • Reduction
    • SDKs
    • GraphQL API
    • Git-style version control
    • App configuration
  • Use Cases
    • Feature flags and A/B testing
    • Landing page optimization
    • In-app content management
    • Pricing plan management
    • Permissions, rules and limits
    • Optimizing magic numbers
    • Backend configuration
    • Product analytics
  • Integrations
    • Vercel Edge Config integration
    • Google Analytics integration
    • Segment integration
    • Webhooks
      • Creating webhooks
      • Handling webhooks
  • SDK Reference
    • Installation
    • Type-safe client generation
    • Initialization
    • Build-time logic snapshot
    • Hard-coded fallbacks
    • Local-only, offline mode
    • Hydrate from your own server
    • Wait for server initialization
    • Provide targeting attributes
    • Local, synchronous evaluation
    • Remote logging
    • Getting flag updates
    • Serverless environments
    • Vercel Edge Config
    • Custom logging
    • Shutting down
Powered by GitBook
On this page
  • 1. Install hypertune
  • 2. Set environment variables
  • 3. Generate the client
  • 4. Use the client
  • 5. (Optional) Include a build-time logic snapshot
  • 6. (Optional) Use Vercel Edge Config
  • 1. Install the integration
  • 2. Use the integration
  • 7. (Optional) Integrate with Vercel's Flags SDK
  • Integrate with the Vercel Toolbar
  • Use Vercel's Flags pattern
  • That's it
  1. Getting Started

Next.js (App Router) quickstart

1. Install hypertune

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

npm install hypertune
yarn add hypertune
pnpm add hypertune

2. Set environment variables

Define the following environment variables in your .env file:

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
yarn hypertune
pnpm hypertune

4. Use the client

Ensure you have the server-only package installed:

npm install server-only
yarn add server-only
pnpm add server-only

Then add a new file called getHypertune.ts that exports a getHypertune function:

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: "hi@test.com" },
      },
    },
  });
}

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

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>;
}

To access flags in the browser in Client Components, first wrap your app with the generated <HypertuneProvider> component in your root layout in app/layout.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 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}</body>
      </html>
    </HypertuneProvider>
  );
}

Then use the generated useHypertune hook:

"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>;
}

Note how we pass serverDehydratedState to <HypertuneProvider>. This instantly hydrates or "bootstraps" the SDK in the browser with the state of the SDK on the server so you can use your flags in the first app render with no layout shift, UI flickers or page load delay. This is optional — if you don't pass this prop, the SDK will initialize as usual in the background and <HypertuneProvider> will trigger a re-render when it's done.

Also note how we pass serverRootArgs to <HypertuneProvider>. This lets you reuse the root args that you used in getHypertune on the server. This is optional — you can also manually create root args for <HypertuneProvider>.

If you have a Content Security Policy, add the following URLs to the connect-src directive: https://edge.hypertune.com https://gcp.fasthorse.workers.dev

This lets the browser send analytics back to Hypertune so you can see how often different parts of your flag logic are evaluated, e.g. to see how many sessions fall into each targeting rule, as well as analytics for your events, A/B tests and machine learning loops.

To access flags in Route Handlers, use the getHypertune function:

import { NextResponse } from "next/server";
import getHypertune from "@/lib/getHypertune";

export const runtime = "edge";

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

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

  return NextResponse.json({ exampleFlag });
}

To access flags in Middleware, use the getHypertune function:

import { NextRequest, NextFetchEvent } from "next/server";
import getHypertune from "@/lib/getHypertune";

export const config = {
  matcher: "/",
};

export async function middleware(
  request: NextRequest,
  context: NextFetchEvent,
) {
  const hypertune = await getHypertune();

  const exampleFlag = hypertune.exampleFlag({ fallback: false });
  console.log("Middleware Example Flag:", exampleFlag);

  context.waitUntil(hypertune.flushLogs());
}

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

Add the following environment variable to your .env file:

HYPERTUNE_INCLUDE_INIT_DATA=true

Then regenerate the client.

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. Select your Vercel team and project.

  2. Continue and log into Hypertune.

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

  4. 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
yarn add @vercel/edge-config
pnpm add @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:

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: "hi@test.com" },
      },
    },
  });
}

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

If your app is deployed on Vercel, you can integrate Hypertune with Vercel's Flags SDK to use:

  • the Vercel Toolbar to view and override your feature flags without leaving your frontend

  • Vercel's Flags pattern

First install the @vercel/flags and @flags-sdk/hypertune packages:

npm install @vercel/flags @flags-sdk/hypertune
yarn add @vercel/flags
pnpm add @vercel/flags

Then generate a Vercel Flags Secret and copy it for later:

node -e "console.log(crypto.randomBytes(32).toString('base64url'))"

Go to your Vercel dashboard, select your project, go to Settings > Environment Variables and add the following:

  1. FLAGS_SECRET, set to your Vercel Flags Secret

  2. HYPERTUNE_ADMIN_TOKEN, set to your Hypertune Admin Token which you can find in the Settings tab of your Hypertune project

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

vercel env pull .env.development.local

Define the following environment variables in your .env file:

HYPERTUNE_PLATFORM=vercel
HYPERTUNE_GET_HYPERTUNE_IMPORT_PATH=@/lib/getHypertune

Replace @/lib/getHypertune with the relative path to your getHypertune function from your generated output directory.

Then regenerate the client:

npx hypertune
yarn hypertune
pnpm hypertune
import "server-only";
import { ReadonlyHeaders } from "next/dist/server/web/spec-extension/adapters/headers";
import { ReadonlyRequestCookies } from "next/dist/server/web/spec-extension/adapters/request-cookies";
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(params?: {
  headers?: ReadonlyHeaders;
  cookies?: ReadonlyRequestCookies;
}) {
  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: "hi@test.com" },
      },
    },
  });
}

Integrate with the Vercel Toolbar

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

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)}</div>
      <VercelFlagValues flagValues={hypertune.get()} />
    </>
  );
}

Finally, add a new route handler in app/.well-known/vercel/flags/route.ts to tell the Vercel Toolbar about your flag definitions:

import { type NextRequest, NextResponse } from 'next/server'
import { verifyAccess, type ApiData } from '@vercel/flags'
import { getProviderData } from '@flags-sdk/hypertune'

export async function GET(request: NextRequest) {
  const access = await verifyAccess(request.headers.get('Authorization'))
  if (!access) {
    return NextResponse.json(null, { status: 401 })
  }
  
  const data = await getProviderData({
    token: process.env.HYPERTUNE_ADMIN_TOKEN!,
  })
  return NextResponse.json<ApiData>(data)
}

Use Vercel's Flags pattern

You can use the generated Vercel feature flag functions to access flags on the server:

import { exampleFlagFlag } from "@/generated/hypertune.vercel";

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

  return <div>Example Flag: {String(exampleFlag)}</div>;
}
import { NextResponse } from "next/server";
import { exampleFlagFlag } from "@/generated/hypertune.vercel";

export const runtime = "edge";

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

  return NextResponse.json({ exampleFlag });
}
import { NextRequest, NextFetchEvent } from "next/server";
import { exampleFlagFlag } from "@/generated/hypertune.vercel";
import getHypertune from "@/lib/getHypertune";

export const config = {
  matcher: "/",
};

export async function middleware(
  request: NextRequest,
  context: NextFetchEvent,
) {
  const exampleFlag = await exampleFlagFlag();
  console.log("Middleware Example Flag:", exampleFlag);

  const hypertune = await getHypertune();
  context.waitUntil(hypertune.flushLogs());
}

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.

PreviousSet up HypertuneNextNext.js (Pages Router) quickstart

Last updated 2 months ago

To keep parts of your app static, adapt the approach in the .

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 .

You can keep the snapshot fresh by setting up a 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.

Go to the and click "Add Integration".

Update your getHypertune function to respect flag overrides set by the Vercel Toolbar and change its signature to accept a params object argument with headers and cookies. Note that changing the signature is only necessary when using as these arguments are passed from the generated code.

First follow .

To use flags on static pages, follow .

Hypertune Edge
webhook
Hypertune page in the Vercel Integrations marketplace
the guide to add the Vercel Toolbar to your local environment
the guide to precompute flags
Vercel's Flag pattern
Pages Router quickstart