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. Update gatsby-config.ts
  • 4. Update .babelrc
  • 5. Generate the client
  • 6. Use the client
  • 7. (Optional) Include a build-time logic snapshot
  • 8. (Optional) Use Vercel Edge Config
  • 1. Install the integration
  • 2. Use the integration
  • That's it
  1. Getting Started

Gatsby quickstart

1. Install hypertune

Once you have a Gatsby application 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.development and .env.production files:

GATSBY_HYPERTUNE_TOKEN=token
HYPERTUNE_FRAMEWORK=gatsby
HYPERTUNE_OUTPUT_DIRECTORY_PATH=src/generated

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

3. Update gatsby-config.ts

Update your gatsby-config.ts to load the environment variables with dotenv:

import type { GatsbyConfig } from "gatsby";

// Load environment variables
require("dotenv").config({
  path: `.env.${process.env.NODE_ENV}`,
});

const config: GatsbyConfig = {
  siteMetadata: {
    title: `Hypertune Gatsby Demo`,
    siteUrl: `https://www.yourdomain.tld`,
  },
  graphqlTypegen: true,
  plugins: [],
};

export default config;

4. Update .babelrc

First install the babel-preset-gatsby package as a devDependency:

npm install -D babel-preset-gatsby
yarn add -D babel-preset-gatsby
pnpm add -D babel-preset-gatsby

Then create a .babelrc at the root of your project:

{
  "presets": [
    [
      "babel-preset-gatsby",
      {
        "targets": {
          "browsers": [">0.25%", "not dead"]
        },
        "exclude": ["@babel/plugin-transform-classes"]
      }
    ]
  ]
}

5. Generate the client

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

npx hypertune
yarn hypertune
pnpm hypertune

6. Use the client

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

import { createSourceForServerOnly } from "../generated/hypertune";

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

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

  return hypertuneSource.root({
    args: {
      context: {
        environment:
          process.env.NODE_ENV === "development"
            ? "development"
            : "production",
        user: { id: "1", name: "Test", email: "hi@test.com" },
      },
    },
  });
}

To access flags in getServerData during Server-side Rendering (SSR), use the getHypertune function:

import * as React from "react";
import { GetServerData } from "gatsby";
import getHypertune from "../lib/getHypertune";

type ServerData = { exampleFlag: boolean };

export const getServerData: GetServerData<
  ServerData
> = async () => {
  const hypertune = await getHypertune();

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

  return { props: { exampleFlag } };
};

export default function Page({
  serverData,
}: {
  serverData: ServerData;
}) {
  return <div>Example Flag: {serverData.exampleFlag}</div>;
}

To access flags in the browser during Client-side Rendering (CSR), first create a new <AppHypertuneProvider> component that wraps the generated <HypertuneProvider> component:

import * as React from "react";
import { HypertuneProvider } from "../generated/hypertune.react";

export default function AppHypertuneProvider({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <HypertuneProvider
      createSourceOptions={{
        token: process.env.GATSBY_HYPERTUNE_TOKEN!,
      }}
      rootArgs={{
        context: {
          environment:
            process.env.NODE_ENV === "development"
              ? "development"
              : "production",
          user: { id: "1", name: "Test", email: "hi@test.com" },
        },
      }}
    >
      {children}
    </HypertuneProvider>
  );
}

Then wrap your app with the <AppHypertuneProvider> component in both gatsby-browser.tsx and gatsby-ssr.tsx:

import * as React from "react";
import type { GatsbyBrowser } from "gatsby";
import AppHypertuneProvider from "./src/components/AppHypertuneProvider";

export const wrapRootElement: GatsbyBrowser["wrapRootElement"] =
  ({ element }) => {
    return (
      <AppHypertuneProvider>{element}</AppHypertuneProvider>
    );
  };

Then use the generated useHypertune hook:

import * as React from "react";
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>;
}

To avoid this, wrap your pages with the generated <HypertuneHydrator> component:

import * as React from "react";
import { GetServerData } from "gatsby";
import {
  DehydratedState,
  RootArgs,
} from "../generated/hypertune";
import { HypertuneHydrator } from "../generated/hypertune.react";
import getHypertune from "../lib/getHypertune";
import ClientComponent from "../components/ClientComponent";

type ServerData = {
  serverDehydratedState: DehydratedState | null;
  serverRootArgs: RootArgs;
};

export const getServerData: GetServerData<
  ServerData
> = async () => {
  const hypertune = await getHypertune();

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

  return { props: { serverDehydratedState, serverRootArgs } };
};

export default function Page({
  serverData,
}: {
  serverData: ServerData;
}) {
  const { serverDehydratedState, serverRootArgs } = serverData;

  return (
    <HypertuneHydrator
      dehydratedState={serverDehydratedState}
      rootArgs={serverRootArgs}
    >
      <ClientComponent />
    </HypertuneHydrator>
  );
}

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 Gatsby Functions, use the getHypertune function:

import {
  GatsbyFunctionRequest,
  GatsbyFunctionResponse,
} from "gatsby";
import getHypertune from "../lib/getHypertune";

export default async function handler(
  req: GatsbyFunctionRequest,
  res: GatsbyFunctionResponse,
) {
  const hypertune = await getHypertune();

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

  res.send({ exampleFlag });
}

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

8. (Optional) Use Vercel Edge Config

If your Gatsby 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. GATSBY_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

Add the environment variables to your .env.development and .env.production files too.

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 { VercelEdgeConfigInitDataProvider } from "hypertune";
import { createClient } from "@vercel/edge-config";
import { createSourceForServerOnly } from "../generated/hypertune";

const hypertuneSource = createSourceForServerOnly({
  token: process.env.GATSBY_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() {
  await hypertuneSource.initIfNeeded(); // Check for flag updates

  return hypertuneSource.root({
    args: {
      context: {
        environment:
          process.env.NODE_ENV === "development"
            ? "development"
            : "production",
        user: { id: "1", name: "Test", email: "hi@test.com" },
      },
    },
  });
}

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.

PreviousRemix quickstartNextVue quickstart

Last updated 10 months ago

If you try accessing a flag immediately after the app loads, you'll get your hardcoded fallback value if the SDK hasn't initialized from yet. This can result in layout shift or UI flickers if the flag value changes when the SDK initializes.

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

Hypertune Edge
Hypertune Edge
webhook
Hypertune page in the Vercel Integrations marketplace