Add edge middleware

You can use Vercel Edge Middleware to execute personalization on the edge. This approach gives you the user experience benefits of server-side rendering with the performance and scalability benefits of a CDN.


For more information about the benefits of executing personalization using Vercel Edge Middleware, see the overview of edge-side personalization.

Next.js 13.1 or later is highly recommended

Next.js 13 introduced a capability to rewrite response body at the edge, which is required to run Uniform edge-side personalization. Uniform specifically recommends using Next.js 13.1 where the feature this capability is built on isn't experimental anymore.

You must have the following available to complete the instructions in this section:

  1. Ability to clone a GitHub repository.
  2. Node.js v16+ installed locally.
  3. An application with edge-side personalization activated.
  4. The application configured to be deployed to Vercel. You can use their free tier if you don't have an account.
  5. The Vercel CLI is installed and configured. See the instructions on this page.
  6. Npm access token from Uniform. Edge-side personalization requires private packages. If you don't have an access token, contact us.

This section explains how to configure and enable edge-side personalization to run on Vercel.

Vercel CLI enables you to send commands to Vercel without having to log into the Vercel dashboard.

  1. Install Vercel CLI with:
    npm i -g vercel
  2. Login to Vercel with:
    vercel login

This guide provides the following options to get started:

  1. Option 1 - if you would like to start with a more feature rich demo to experience the power of edge-side personalization.
  2. Option 2 - if you would like to go through all the steps to add an edge function into your application and understand all the mechanics first.

This section guides you through the process of getting a pre-built sample application deployed and running on Vercel with personalization executed using Vercel Edge Middleware.


Don't use this application as a foundation or starting point to build your own application. This is a sample app designed to demonstrate edge-side personalization using Vercel Edge Middleware.

If you have your own personalized application and you want it to run on Vercel using Vercel Edge Middleware, see this option instead.

  1. Open a terminal and enter the following:

    git clone
    cd examples/context-edge-vercel
  2. Ensure your npm access token is configured correctly.

    About this step

    The sample code includes a file .npmrc that's set to look for an environment variable NPM_TOKEN. You can set an environment variable on your workstation to your npm access token to meet this requirement.

    Another option is to set your npm access token directly in the .npmrc file.

  3. Enter the following command:

    npm install

    About this step

    If you get an error like the following, the problem is most likely that either you do have your npm access token configured correctly, or the access token has expired.

    '@uniformdev/context-edge@^17.0.0' is not in this registry.
  4. Enter the following command:

    vercel --build-env NPM_TOKEN=[!!! YOUR NPM TOKEN !!!] --prod

    You must replace [!!! YOUR NPM TOKEN !!!] with your npm access token.

  5. After the application is deployed, you can visit the site to see personalization executed by Vercel Edge Middleware. You can now disable JavaScript and experience personalization without any JS runtime!

This section guides you through the process of activating edge-side personalization on an existing web application using Vercel Edge Middleware.

Follow this guide to get your web app instrumented with Uniform Context SDK and configured to run in edge mode by following this guide.

Don't forget

There are two crucial steps you must configure in order for the rest of the steps to work:

  1. NextCookieTransitionDataStore is configured
  2. outputType="edge" is set on UniformContext:<UniformContext outputType="edge" />`

This section gets you to having a Vercel Edge Middleware that can execute Uniform personalization instructions as quickly as possible. It doesn't explain each line of code.

  1. Add the following environment variable to your workstation:

    NPM_TOKENThe npm access token from Uniform.

    About this step

    You can't set this value in the .env file. That file defines environment variables available within your app, while this environment is needed by another app (such as npm).

    You can set the environment variable to be system wide or just active in your current terminal.

  2. Add the .npmrc file to the root of your application:

    //${NPM_TOKEN} engine-strict = true
  3. Run the following command to install two packages - cookie and context-edge-vercel:

    npm i cookie @uniformdev/context-edge-vercel
  4. Add the middleware.ts file into the same level as your /pages directory:

    File location is important

    Please double check the location of this file. It should be located in the same level as the /pages directory. If this file is placed in incorrect location, Vercel won't build and deploy edge middleware.

    import { parse } from "cookie"; import { NextRequest, NextResponse } from "next/server"; import { Context, CookieTransitionDataStore, ManifestV2, UNIFORM_DEFAULT_COOKIE_NAME, } from "@uniformdev/context"; import { createUniformEdgeMiddleware } from "@uniformdev/context-edge-vercel"; import manifest from "./lib/uniform/context-manifest.json"; export const config = { matcher: [ /* * Match all request paths except for the ones starting with: * - _next * - static (static files) * - favicon.ico (favicon file) */ "/(.*?trpc.*?|(?!static|.*\\..*|_next|images|img|api|favicon.ico).*)", ], }; export async function middleware(request: NextRequest) { const data = request.headers.get("x-nextjs-data"); const previewDataCookie = request.cookies.get("__next_preview_data"); const { nextUrl: { search }, } = request; const urlSearchParams = new URLSearchParams(search); const params = Object.fromEntries(urlSearchParams.entries()); // disabling middleware in preview or locally if ( Boolean(previewDataCookie) || Boolean(data) || params.is_incontext_editing_mode === "true" || !process.env.VERCEL_URL ) { return; } const serverCookieValue = request ? parse(request.headers.get("cookie") ?? "")[UNIFORM_DEFAULT_COOKIE_NAME] : undefined; const context = new Context({ defaultConsent: true, manifest: manifest as ManifestV2, transitionStore: new CookieTransitionDataStore({ serverCookieValue, }), }); const handler = createUniformEdgeMiddleware(); const response = await handler({ context, origin: new URL(request.url), request, }); response.headers.set("Cache-Control", "no-cache, no-store, must-revalidate"); return response; }

    About this step

    The manifest import statement assumes the name and location of your Uniform manifest. If you file is in another location, you will need to change this statement.

  5. Only if you are running a version of Next.js earlier than 13.1, you will need to add a special experimental setting to allow the edge middleware to modify the response body, add allowMiddlewareResponseBody=true to next.config.js:

    const nextConfig = { experimental: { allowMiddlewareResponseBody: true, }, }; module.exports = nextConfig;

You can run the build locally with:

npm run build

Run the following command to build your app locally and deploy to Vercel:

vercel --build-env NPM_TOKEN=[!!! YOUR NPM TOKEN !!!] --prod

You must replace [!!! YOUR NPM TOKEN !!!] with your npm access token. After the application is deployed, you can visit the site to see personalization executed by Vercel Edge Middleware.

You can confirm personalization is running in Vercel if you have personalization based on a query string parameter. Disable JavaScript on your browser and then view a page with personalization. If you see personalized content, you know the personalization was executed in Vercel.

Next steps

Now that you have Vercel delivering edge-side personalization, you might want to take advantage of another feature available when you run personalization using Vercel Edge Middleware: location-based personalization.