Skip to main content
This comprehensive tutorial will walk you through setting up Sanity with GrowthBook for A/B testing in a Next.js application. You’ll learn how to create content variations with Sanity and use GrowthBook for feature flag experiments like in the example below. Sanity is a real-time content backend for all your text and assets. Sanity Studio is a flexible, multiplayer TypeScript CMS which is configured with code and deployed to your authors. In this guide you’ll embed it as part of your Next.js application, but it can also be deployed standalone. GrowthBook (that’s us!) is open source feature flag management and experimentation platform that works great with your stack—including Sanity. For the purposes of this guide, we’ll be creating an A/B test for the product page of a fictional camera store, Camera World.
Two variations of Camera World with different titles and images

Prerequisites

Video Tutorial

Set up Next.js and Sanity

Install Next.js

Already have a Next.js project? Skip to the next section.

Install Sanity

Inside your Next.js project, install Sanity:
Choose the default options when prompted. This creates Sanity Studio inside your Next.js project (accessible at /studio) and sets up the necessary config files.
Free Sanity account requiredYou’ll need a free Sanity account to complete this guide, if you do not yet have one, you will be prompted to create one after running this command.

Add the Sanity Personalization Plugin

Sanity offers a plugin for personalization that includes a direct integration with GrowthBook. This plugin allows you to create content variations within Sanity and use GrowthBook for feature flag experiments. Install the plugin:

Update your Sanity config

In your Next.js project, update sanity.config.ts to include the personalization plugin. Note that the fields listed below are the existing defined fields that you are extending to be able to experiment on. (Changes highlighted in the code block below.)

Add Experiment Fields to Your Sanity Schema

With the personalization plugin installed, you can now add experiment fields to your Sanity schema. Create a new file sanity/schemaTypes/camera.ts:
The schema uses experimentString and experimentImage field types (highlighted in the code block above) provided by the personalization plugin. These allow you to create content variations with Sanity and use GrowthBook for experiments. Import the schema into your sanity/schemaTypes.ts file:

Add Queries to Fetch Experiment Content

Create a new file sanity/lib/queries.ts to store your GROQ query:
This query fetches the experiment content and serves the appropriate variation to the user.
Type generationRun npx sanity@latest schema extract && npx sanity@latest typegen generate in your project to generate types for your queries/schema automatically.

Configure GrowthBook

In this section, we’ll create an SDK connection, feature flag, and experiment in GrowthBook.
  • The SDK connection links GrowthBook to your Next.js app.
  • Feature flags live in your codebase and control which code is executed.
  • Experiments are defined as feature flag rules and are used to test different variations.

Create a GrowthBook SDK Connection

GrowthBook SDK Connection
  1. In GrowthBook, go to SDK ConfigurationSDK Connections and click Add SDK Connection.
  2. Choose Node.js and click Save.
  3. Copy the Client Key and add it to your .env.local in Next.js. (You’ll also see the environment variables for Sanity in the file.)
Update env variablesRemember to update environment variables with your hosting provider when you deploy your app.

Create a Feature Flag

For our Camera World example, let’s test the title, description, and image for the Sony A7 IV product page.
GrowthBook Feature Flag
  1. In GrowthBook, go to Features and click Add Feature.
  2. Give the feature a name, like flag-sony-a7-iv.
  3. Set the value type to String.
  4. Set the default value to “control”.
  5. Save the feature.

Create an Experiment

With the feature flag created, we can now create an experiment.
GrowthBook Experiment
  1. On the same page, scroll down to Rules and click Add Rule.
  2. Select Experiment.
  3. Configure your experiment:
  • Name: “Sony A7 IV Experiment”
  • Control: “control”
  • Variation 1: “variation”
  1. Complete remaining steps and save.
  2. Click Review and Publish to launch the experiment.
Your experiment is now live! Before creating the content variations with Sanity, we’ll need to create an API Key that allows Sanity to fetch the experiment content.

Create an API Key

  1. In GrowthBook, go to SettingsAPI Keys
  2. Click New Secret Key
  3. Add a description, like Sanity API Key.
  4. Set the role to readonly.
  5. Save and copy the API key for the next step.

Add Content Variations with Sanity

In Sanity Studio, we’ll open the Camera Product document for the Sony A7 IV. While our control uses matter-of-fact language, the variation will be more exciting.
API key requiredThe first time you open document an experiment field, you’ll be prompted to enter the API key you created in the previous step.
  1. Add your default content.
  2. Hover over the Title, Description, and Image fields to reveal an experiment (flask) icon.
  3. Click the experiment icon to open a dropdown where you can select the experiment you created in GrowthBook.
  4. Add content for each variation:
  • Control: Your default content
  • Variation: Alternative title/image to test
  1. Publish content!
Here’s what the experiment fields look like in Sanity Studio:
Sanity Experiment Field
Add flag to field
Sanity experiment

Add GrowthBook to Your Next.js App

Now, let’s integrate GrowthBook in your Next.js app to serve the appropriate content to the user.

Install GrowthBook

Configure GrowthBook for Server-Side Rendering

Create a new file, lib/growthbookServer.ts:

Configure Experiment Tracking

To track experiment exposures—which variations a users saw—we’ll need to create a tracking component. Create a new file, lib/growthbookTracking.tsx. Note the TODO comment. You’ll need to replace the console.log with your own event tracking. Popular event tracking tools include Google Analytics, Segment, and Jitsu.

Update Middleware for Consistent User IDs

Create or update middleware.ts in your project root to ensure consistent experiment assignment.

Bring Everything Together in Your Next.js App

Now let’s create a page that demonstrates the A/B testing functionality. It’s a dynamic route that fetches the product data from Sanity and serves the appropriate content to the user. The relevant part of the template is highlighted in the code block below.
Sanity experiment: a

Sanity experiment: Control

Sanity experiment: b

Sanity experiment: Variation

Create an Experiment Page

Edit app/[slug]/page.tsx:

Testing Your Setup

With your Next.js app running, you can now test the A/B testing functionality. Visit the app in your browser to see which variation is being served. Even when you refresh the page, the same variation will be served to the user. Check your console to see debug info.
Clear or override the GB_UUID_COOKIE to see different variations

Next Steps

  • Add Event Tracking: Replace the console.log with your analytics service (Google Analytics, Segment, etc.) See docs for more details.
  • Add Metrics: Add metrics to your experiment to track conversions, revenue, etc.
  • Configure Webhooks: Set up GrowthBook webhooks to revalidate your Next.js cache when experiments change

Troubleshooting

  • No variations showing: Check that your GrowthBook client key is correct and the experiment is published.
  • Console errors: Check that all environment variables are set correctly.
  • Other issues: Restart your Next.js app and open an incognito window to test.
This setup provides a foundation for content-driven A/B testing with Sanity and GrowthBook. The integration allows content creators to manage experiment variations directly in Sanity Studio while developers control the experiment logic through GrowthBook.