Middleware

This demo is easiest to understand if you open its source code in a parallel tab.

Source code

This demo shows how to use @happykit/flags in Next.js Middleware.

You have been served the "full" checkout variant.

This example uses a _middleware file at pages/demo/middleware to statically render different variants for the /demo/middleware path. The different variants live under pages/demo/middleware/variant-*.tsx.

The middleware loads the flags and rewrites the incoming request either to variant-short.tsx, variant-medium.tsx or variant-full.tsx depending on the resolved flag variant.

Since resulting page is served statically from the edge, rendering will use no visitor key. This is necessary as the concept of a visitor does not exist during static site generation. Thus all rules and percentage-based rollouts targeting a visitor resolve to null.

The middleware loads the flags purely to decide where to rewrite the request to. It does not send any resolved flags into the application itself.

You are however free to call useFlags() on the client and combine this approach with the middleware.