Skip to Content

Examples

Next.js + Vercel

Next.js middleware reading the datafile from Vercel Global Config

2 min read

This is the Next.js example with one change: instead of fetching the datafile from Improve inside the middleware, it reads it from Vercel Global Config. Global Config is replicated next to the middleware, and Next.js does not cache fetch in middleware, so this is what removes the round trip from every request.

Only the active state is mirrored, so the code falls back to fetchConfig for any other state.

Install

npm i @obelism/improve-sdk @obelism/improve-sdk-next @vercel/global-config

Middleware

getAll() is one read for all three environments. ImproveServerSDK takes the config directly, so no fetch happens in the common case.

src/middleware.ts
import { type NextRequest } from 'next/server'
import { getAll } from '@vercel/global-config'
import { ImproveServerSDK } from '@obelism/improve-sdk/server'
import { generateImproveNextMiddleware } from '@obelism/improve-sdk-next'
import type { ImproveConfiguration } from '@obelism/improve-sdk/types'

import { IMPROVE_CONFIG } from './app/improveConfig'

export const config = {
	matcher: '/',
}

const improveSdk = new ImproveServerSDK(IMPROVE_CONFIG)

const handler = generateImproveNextMiddleware({
	improveSdk,
	serverABtests: [
		{
			slug: 'startpage-visual',
			routeHandler: '/',
			options: [
				{ value: 'control', slug: '/' },
				{ value: 'variation', slug: '/variation' },
			],
		},
	],
})

const loadConfig = async () => {
	const config = (await getAll())?.[IMPROVE_CONFIG.environment] as
		ImproveConfiguration | undefined
	if (config) return improveSdk.loadConfig(config)

	// The store is empty or unreachable: the API is always right.
	return improveSdk.fetchConfig()
}

export const middleware = async (request: NextRequest) => {
	await loadConfig()
	return handler(request)
}

IMPROVE_CONFIG is the same object the Next.js example uses: the organization id, the environment, a token from the environment's API tokens, and optionally spaceId. Keep the token out of version control:

This reads the active state. A draft or a finished test comes from the API, as the plain Next.js example shows.

src/app/improveConfig.ts
export const IMPROVE_CONFIG = {
	organizationId: process.env.IMPROVE_ORGANIZATION_ID!,
	spaceId: process.env.IMPROVE_SPACE_ID!,
	environment: (process.env.IMPROVE_ENVIRONMENT ?? 'production') as
		'develop' | 'staging' | 'production',
	token: process.env.IMPROVE_API_TOKEN!,
}

Setting the store up is the Vercel integration: Settings → Integrations, paste a token, then attach the store to the project in Vercel's Storage.

On this page

Marks in the margin

  • Note
  • Watch out
  • Updated

Scribes marked doubtful lines in the margin. That practice is called obelism.