Quickstart for Using Edge Middleware
In this quickstart guide, you'll learn how to get started with Next.js Middleware and using Edge Middleware in Vercel CLIIn this quickstart guide, you'll learn how to get started with Next.js Middleware and using Edge Middleware in the Vercel CLI. For information on the API and how to use it, see the Edge Middleware API documentation.
If you would prefer to jump straight into code examples, see the Edge Middleware templates .
You should have the latest version (>= v25) of the Vercel CLI. To check your version, use vercel --version
. To install or update Vercel CLI, use:
pnpm i -g vercel@latest
Before you begin, ensure that your app is using the most recent version of Next.js:
pnpm i next
Edge Middleware runs before the incoming request and cache, which allows you to personalize cached content. In this quickstart you will create a middleware that runs on a specific route (/secret-page
). If your visitor is from a specific geographic location, and visits the /secret-page
route, the request will be rewritten to a /login
page instead.
After completing this quickstart you will have learnt how to:
- Use the
geolocation
helper method from@vercel/functions
to personalise the content based on the visitor's location - Use the custom match config to trigger the middleware to run on a specific route - Edge Middleware is invoked for every route in the app by default
- Rewrite to a new URL
Use
create-next-app
to create a new Next.js project or use your existing project:terminalnpx create-next-app@latest --typescript
Follow the prompts to set your project up. You'll be using the TypeScript variant of the starter project as you will be importing some helpers from
next/server
in later steps.Then, create a
middleware.ts
(or.js
) file at the same level as yourpages
orapp
directory (even if you're using asrc
directory). This is where the code that will be deployed as middleware will live. The file extension can be.ts
or.js
, this guide uses TypeScript.For this quickstart, you should also add some new helper directories to your project:
secret-page
, andlogin
. Your folder structure should have the following layout:The content of these pages are not relevant to this quickstart, but they are used to demonstrate the use of the middleware.
app/secret-page/page.tsxexport default function SecretPage() { return ( <div> <h1>Secret Page</h1> <p>This is a secret page!</p> </div> ); }
@vercel/functions
provides a helper methodgeolocation
which can be used to fetch the geo location of the visitor.pnpm i @vercel/functions
The following middleware code takes the geographic location of the visitor from the request, and rewrites the request to a login page if they are from SE (Sweden).
When copying this code into your project, you will need to replace the
BLOCKED_COUNTRY
variable with the ISO Alpha-2 code of your location. You can look up this value on the IBAN country code list.middleware.tsimport { NextRequest, NextResponse } from 'next/server'; import { geolocation } from '@vercel/functions'; // The country to block from accessing the secret page const BLOCKED_COUNTRY = 'SE'; // Trigger this middleware to run on the `/secret-page` route export const config = { matcher: '/secret-page', }; export default function middleware(request: NextRequest) { // Extract country. Default to US if not found. const { country = 'US' } = geolocation(request); console.log(`Visitor from ${country}`); // Specify the correct route based on the requests location if (country === BLOCKED_COUNTRY) { request.nextUrl.pathname = '/login'; } else { request.nextUrl.pathname = `/secret-page`; } // Rewrite to URL return NextResponse.rewrite(request.nextUrl); }
If you're not using a framework, you must either add
"type": "module"
to yourpackage.json
or change your JavaScript Functions' file extensions from.js
to.mjs
When working locally, your IP address will be 127.0.0.1. This means that the
geolocation
can't be computed and the middleware location check will default toUS
(as defined in step five).To test your middleware, use the Vercel CLI to deploy your project with
vercel deploy
.Once deployed, open the production url, and edit the url to
https://<your-project-name>.vercel.app/secret-page
, you should be redirected to the/login
page.Edit the
BLOCKED_COUNTRY
variable to a country you are not in and deploy again withvercel deploy
. You should now be able to access the/secret-page
route.Once your Function is published, go to your project's overview page from your Vercel dashboard and click the Logs tab. This tab allows you to view, search, inspect, and share your runtime logs invoked by Edge Middleware.
To view details for these logs click any individual log entry. The information will appear in the right sidebar.
You have created a new Next.js project and deployed Edge Middleware. Based on the incoming requests location, you have rewritten the request to a login page.
- Edge Middleware runs before the cache
- You can import helpers that extend Web API objects (NextResponse, NextRequest, see Edge Middleware API for more information on these APIs)
- You can use a custom matcher config to only trigger the middleware in specific routes
- You cannot use Node.js APIs in Edge Middleware
To learn more about Edge Middleware, and its use cases, see the Edge Middleware documentation.
Was this helpful?