Feature Flags in Edge Middleware
Shows how to use feature flags in Edge Middleware to serve different static variants of a page.
Example
This example works by using a feature flag in Edge Middleware to then
rewrite the request to a different page. Rewriting the request means the
user-facing URL shown in the browser stays the same, while different
content is served for different visitors. As the underlying
variant-on
and variant-off
pages are static,
the CDN or Edge Network can serve these at the edge.
import { type NextRequest, NextResponse } from 'next/server';import { basicEdgeMiddlewareFlag } from './flags';
export const config = { matcher: ['/examples/feature-flags-in-edge-middleware'],};
export async function middleware(request: NextRequest) { const active = await basicEdgeMiddlewareFlag(); const variant = active ? 'variant-on' : 'variant-off';
return NextResponse.rewrite( new URL( `/examples/feature-flags-in-edge-middleware/${variant}`, request.url, ), );}
Advanced examples
Using feature flags in Edge Middleware as shown in this example is very basic. This approach does not scale well when you have are using multiple feature flags on the same page or when you are using the same feature flag on multiple pages. We recommend using precompute for more advanced use cases, which solves these challenges.