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.
tip
For more information about the benefits of executing personalization using Vercel Edge Middleware, see the overview of edge-side personalization.
Before you start#
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:
- Ability to clone a GitHub repository.
- Node.js v16+ installed locally.
- An application with edge-side personalization activated.
- The application configured to be deployed to Vercel. You can use their free tier if you don't have an account.
- The Vercel CLI is installed and configured. See the instructions on this page.
- 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.
Configure CLI#
Vercel CLI enables you to send commands to Vercel without having to log into the Vercel dashboard.
Pick your journey#
This guide provides the following options to get started:
- Option 1 - if you would like to start with a more feature rich demo to experience the power of edge-side personalization.
- 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.
Option 1: Quick start demo#
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.
tip
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.
Open a terminal and enter the following:
git clone https://github.com/uniformdev/examples.gitcd examples/context-edge-vercelEnsure 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 variableNPM_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.Enter the following command:
npm installAbout 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.Enter the following command:
vercel --build-env NPM_TOKEN=[!!! YOUR NPM TOKEN !!!] --prodYou 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 now disable JavaScript and experience personalization without any JS runtime!
https://yourapp.vercel.app/?utm_campaign=unfrmconf
Option 2: Add edge-side personalization into your application#
This section guides you through the process of activating edge-side personalization on an existing web application using Vercel Edge Middleware.
Step 1: Add Uniform Context into your app#
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:
NextCookieTransitionDataStore
is configuredoutputType="edge" is set on UniformContext:
<UniformContext outputType="edge" />`
Step 2: Add Vercel Edge Middleware#
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.
Add the following environment variable to your workstation:
Name Value NPM_TOKEN
The 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.
Add the
.npmrc
file to the root of your application://registry.npmjs.org/:_authToken=${NPM_TOKEN} engine-strict = trueRun the following command to install two packages -
cookie
andcontext-edge-vercel
:npm i cookie @uniformdev/context-edge-vercelAdd 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 NextResponse.next(); } 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.
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;
Step 3: Build the app#
You can run the build locally with:
Step 4: Deploy your application#
Run the following command to build your app locally and deploy to Vercel:
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.