Skip to content

Edge Middleware Quickstart

Learn how to get started with Edge Middleware on Vercel.

In this quickstart guide, you'll learn how to get started with Edge Middleware using the Vercel CLI, or Next.js. For information on the API and how to use it, see the Edge Middleware API documentation.

You should have the latest version (>= v25) of the Vercel CLI. To check your version, use vc --version. To install or update the CLI, use:

npm i -g vercel@latest

Before you begin, ensure that your app is using the most recent version of Next.js:

npm install next@canary

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 geo object 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:

npx 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.

First, Create a middleware.ts (or .js) file at the same level as your pages 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 files in the pages directory: secret-page.tsx, and login.tsx. Your folder structure should look like the following:

The content of these pages are not relevant to this guide, but they are used to demonstrate the use of the middleware.

// secret-page.tsx

export default function SecretPage() {
  return (
    <div>
      <h1>Secret Page</h1>
      <p>This is a secret page!</p>
    </div>
  );
}
// login.tsx

export default function Login() {
  return (
    <div>
      <h1>Login Page</h1>
      <p>This is the login page</p>
    </div>
  );
}

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.ts

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

// 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 function middleware(req: NextRequest) {
  // Extract country. Default to US if not found.
  const country = (req.geo && req.geo.country) || 'US';

  console.log(`Visitor from ${country}`);

  // Specify the correct route based on the requests location
  if (country === BLOCKED_COUNTRY) {
    req.nextUrl.pathname = '/login';
  } else {
    req.nextUrl.pathname = `/secret-page`;
  }

  // Rewrite to URL
  return NextResponse.rewrite(req.nextUrl);
}

When working locally, your IP address will be 127.0.0.1. This means that the geo location can't be computed and the middleware location check will default to US (as defined in step four).

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 with vercel deploy. You should now be able to access the /secret-page route.

Once your Function is published, you can select your app from your Vercel dashboard to see the deployments. You can view live details in the Functions tab of your application or by clicking the View Function Logs button.

The Functions tab will show you logs from any running functions within your project. Use the dropdown to select the middleware function.

The runtime of the function will read Edge, and the region will be the closest region to you. In addition, you should see the logged location of the request, your location.

The Functions tab showing the runtime and region of the middleware function, along with the logged location of the visitor.

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
  • Edge Middleware cannot return responses
  • You cannot use Node.js APIs in Edge Middleware

To learn more about Edge Middleware, and its use cases, see the Edge Middleware documentation.