Comment on page
Gatsby quickstart
Once you have a Gatsby application ready, install Hypertune's JavaScript SDK:
npm
yarn
pnpm
npm install hypertune
yarn add hypertune
pnpm add hypertune
Define the following environment variables in your
.env.development
and .env.production
files:GATSBY_HYPERTUNE_TOKEN=token
HYPERTUNE_OUTPUT_FILE_PATH=src/generated/generated.ts
Replace
token
with your project token which you can find in the Settings tab of your project.Update your
gatsby-config.js
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;
Create a
.babelrc
in the root of your project if you don't have one yet. Then update it to exclude @babel/plugin-transform-classes
:{
"presets": [
[
"babel-preset-gatsby",
{
"targets": {
"browsers": [">0.25%", "not dead"]
},
"exclude": ["@babel/plugin-transform-classes"]
}
]
]
}
Generate a type-safe client to access your flags by running:
npm
yarn
pnpm
npx hypertune
yarn hypertune
pnpm hypertune
Add a new file called
hypertune.ts
that creates and exports a hypertune
singleton:import { initializeHypertune } from "../generated/generated";
const hypertune = initializeHypertune({}, {
token: process.env.GATSBY_HYPERTUNE_TOKEN
});
export default hypertune;
Then import and use this
hypertune
singleton to access your flags with end-to-end type-safety:Server-side Rendering
Partial Hydration
Functions
To access flags in
getServerData
for Server-side Rendering (SSR), use the hypertune
singleton directly:import { GetServerData } from "gatsby";
import * as React from "react";
import hypertune from "../lib/hypertune";
import { InitResponseBody } from "hypertune";
import ClientExample from "../lib/ClientExample";
type ServerData = {
exampleFlag: boolean;
hypertuneInitData: InitResponseBody | null;
};
export const getServerData: GetServerData<ServerData> = async () => {
await hypertune.initFromServerIfNeeded();
const rootNode = hypertune.root({
context: {
user: { id: "test_id", name: "Test", email: "[email protected]" },
},
});
const exampleFlag = rootNode.exampleFlag().get(/* fallback */ false);
return {
props: { exampleFlag, hypertuneInitData: hypertune.getInitData() },
};
};
function Page({ serverData }: { serverData: ServerData }) {
return (
<div>
<div>
Server-side props flag:
{String(serverData.exampleFlag)}
</div>
<ClientExample hypertuneInitData={serverData.hypertuneInitData} />
</div>
);
}
export default Page;
To access flags on the client, first define a
useHypertune
hook in a new file called useHypertune.ts
:import React, { useEffect, useMemo } from "react";
import hypertune from "./hypertune";
export default function useHypertune() {
// Trigger a re-render when flags are updated
const [, setCommitHash] = React.useState<string | null>(
hypertune.getCommitHash(),
);
useEffect(() => {
hypertune.addUpdateListener(setCommitHash);
return () => {
hypertune.removeUpdateListener(setCommitHash);
};
}, []);
// Return the Hypertune root node initialized with the current user
return useMemo(
() =>
hypertune.root({
context: {
user: { id: "test_id", name: "Test", email: "[email protected]" },
},
}),
[],
);
}
Then use the hook:
import { InitResponseBody } from "hypertune";
import hypertune from "./hypertune";
import useHypertune from "./useHypertune";
export default function ClientExample({
hypertuneInitData,
}: {
hypertuneInitData?: InitResponseBody | null;
}): React.ReactElement {
if (hypertuneInitData) {
hypertune.initFromData(hypertuneInitData);
}
const rootNode = useHypertune();
const exampleFlag = rootNode.exampleFlag().get(/* fallback */ false);
return <div>Client Component flag: {String(exampleFlag)}</div>;
}
To access flags in React Server Components for Partial Hydration, use the
hypertune
singleton directly:import ClientExample from "./ClientExample";
import hypertune from "./hypertune";
export default async function ServerExample() {
await hypertune.initFromServerIfNeeded();
const rootNode = hypertune.root({
context: {
user: { id: "test_id", name: "Test", email: "[email protected]" },
},
});
const exampleFlag = rootNode.exampleFlag().get(/* fallback */ false);
return (
<>
<div>Server Component flag: {String(exampleFlag)}</div>
<ClientExample hypertuneInitData={hypertune.getInitData()} />
</>
);
}
To access flags in Client Components, first define a
useHypertune
hook in a new file called useHypertune.ts
:import React, { useEffect, useMemo } from "react";
import hypertune from "./hypertune";
export default function useHypertune() {
// Trigger a re-render when flags are updated
const [, setCommitHash] = React.useState<string | null>(
hypertune.getCommitHash()
);
useEffect(() => {
hypertune.addUpdateListener(setCommitHash);
return () => {
hypertune.removeUpdateListener(setCommitHash);
};
}, []);
// Return the Hypertune root node initialized with the current user
return useMemo(
() =>
hypertune.root({
context: {
user: { id: "test_id", name: "Test", email: "[email protected]" },
},
}),
[]
);
}
Then use the hook:
"use client";
import { InitResponseBody } from "hypertune";
import hypertune from "./hypertune";
import useHypertune from "./useHypertune";
export default function ClientExample({
hypertuneInitData,
}: {
hypertuneInitData?: InitResponseBody | null;
}): React.ReactElement {
if (hypertuneInitData) {
hypertune.initFromData(hypertuneInitData);
}
const rootNode = useHypertune();
const exampleFlag = rootNode.exampleFlag().get(/* fallback */ false);
return <div>Client Component flag: {String(exampleFlag)}</div>;
}
To access flags in Gatsby Functions, use the
hypertune
singleton directly:import { GatsbyFunctionRequest, GatsbyFunctionResponse } from "gatsby";
import hypertune from "../lib/hypertune";
export default async function handler(
req: GatsbyFunctionRequest,
res: GatsbyFunctionResponse,
) {
await hypertune.initFromServerIfNeeded();
const rootNode = hypertune.root({
context: {
user: { id: "test_id", name: "Test", email: "[email protected]" },
},
});
const exampleFlag = rootNode.exampleFlag().get(/* fallback */ false);
console.log("Gatsby Functions flag:", exampleFlag);
res.send({ exampleFlag });
}
Notice how we passed the
ClientExample
component a prop with the result of hypertune.getInitData()
on the server. This shows how you can immediately "bootstrap" the SDK on the client with the state of the SDK from the server. This lets you use your flag in the first app render without any page load delay, UI flicker or layout shift. This is optional; if you don't bootstrap the SDK on the client in this way, it will initialize as usual in the background and the useHypertune
hook will trigger a re-render when it's done.If you're using Hypertune in the browser and have a Content Security Policy, add the following URLs to the
connect-src
directive: https://edge.prod.hypertune.com https://gcp.fasthorse.workers.dev
This allows analytics to be sent back to Hypertune so you can see how often different parts of your flag logic are called, 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.
If you don't "bootstrap" the SDK on the client with the state of the SDK from the server, as described above, and you try accessing your flag on the first app render, you'll get your hardcoded fallback value if the SDK hasn't had a chance to initialize from Hypertune Edge yet. This can result in a UI flicker or layout shift if the flag value changes when the SDK initializes. To avoid this, you can include a snapshot of your flag logic in the generated client as a build-time fallback.
Add the following environment variable to your
.env
file:HYPERTUNE_INCLUDE_FALLBACK=true
Then regenerate the client.
The SDK will now instantly initialize from the snapshot first before fetching the latest flag logic from Hypertune Edge. And it will always successfully initialize, even if Hypertune Edge is unreachable. You can keep the snapshot fresh by setting up a webhook to regenerate the client on every Hypertune commit.
If you don't want to include the snapshot but still want to avoid UI flickers and layout shift, you can explicitly wait for initialization from Hypertune Edge with
await hypertune.initFromServerIfNeeded()
or check for initialization from Hypertune Edge with hypertune.hasInitializedFromServer()
.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.
- 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
Add the environment variables to your
.env.development
and .env.production
files too.Install the Vercel Edge Config package:
npm
yarn
pnpm
npm install @vercel/edge-config
yarn add @vercel/edge-config
pnpm add @vercel/edge-config
Update your
hypertune.ts
to create an Edge Config client and pass it along with your Edge Config Item Key when initializing the Hypertune SDK:import { createClient } from "@vercel/edge-config";
import { initializeHypertune } from "./generated/generated";
const edgeConfigClient = process.env.EDGE_CONFIG
? createClient(process.env.EDGE_CONFIG)
: undefined;
const hypertune = initializeHypertune({},
{
token: process.env.GATSBY_HYPERTUNE_TOKEN,
vercelEdgeConfigClient: edgeConfigClient,
vercelEdgeConfigItemKey: process.env.EDGE_CONFIG_HYPERTUNE_ITEM_KEY,
},
);
export default hypertune;
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 modified 20d ago