Next.js + Vercel
Next.js middleware reading the datafile from Vercel Edge Config
This is the Next.js example with one change: instead of fetching the config over the network inside the middleware, it reads the datafile from Vercel Edge Config. Edge Config is co-located with the middleware, so there is no network round-trip on every request.
The Vercel integration keeps your Edge Config in sync with the active tests, flags and audiences. Only the active state is synced, so the example falls back to a regular fetchConfig for any other state (e.g. when testing a draft).
Install
npm i @obelism/improve-sdk @obelism/improve-sdk-next @obelism/improve-sdk-react @vercel/edge-configMiddleware
The only difference from the plain Next.js example is getImproveConfig: it loads the datafile from Edge Config with loadConfig when the state is active, and fetches it from the API otherwise.
import { type NextRequest } from 'next/server'
import { get as getFromEdgeConfig } from '@vercel/edge-config'
import { type ImproveConfiguration } from '@obelism/improve-sdk/types'
import { ImproveServerSDK } from '@obelism/improve-sdk/server'
import { generateImproveNextMiddleware } from '@obelism/improve-sdk-next'
import { IMPROVE_CONFIG } from './app/improveConfig'
export const config = {
matcher: '/',
}
const improveSdk = new ImproveServerSDK({
...IMPROVE_CONFIG,
token: 'xxxx-xxxx-xxxx-xxxx',
})
const improveMiddlewareHandler = generateImproveNextMiddleware({
improveSdk,
serverABtests: [
{
slug: 'startpage-visual',
routeHandler: '/',
options: [
{ value: 'control', slug: '/' },
{ value: 'variation', slug: '/variation' },
],
},
],
})
const getImproveConfig = async () => {
if (!!improveSdk.config) return
// Only the active state is saved in edge config
if (IMPROVE_CONFIG.state !== 'active') {
return await improveSdk.fetchConfig()
}
const config = await getFromEdgeConfig(IMPROVE_CONFIG.environment)
improveSdk.loadConfig(config as ImproveConfiguration)
}
export const middleware = async (request: NextRequest) => {
await getImproveConfig()
return improveMiddlewareHandler(request)
}Note: the runnable example hardcodes the server token for brevity. In your own app load it from an environment variable so it never ends up in version control.
Everything else — the shared config, client provider, routes and analytics tracking — is identical to the Next.js example.