Gatsby quickstart

1. Install hypertune

Once you have a Gatsby application ready, install Hypertune's JavaScript SDK:

npm install 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

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

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

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

HYPERTUNE_INCLUDE_INIT_DATA=true

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

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

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.

Last updated