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 Vercel CLI, use:


npm i -g vercel

Updating Vercel CLI using the npm command.

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


npm i next@latest

Updating Next.js using the npm command.

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:

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

pages/secret-page.tsx
export default function SecretPage() {
  return (
    <div>
      <h1>Secret Page</h1>
      <p>This is a secret page!</p>
    </div>
  );
}
pages/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.

Edge Middleware runs before the incoming request, and cache. This means that you can personalize cached content. In this guide you will create a middleware that will check which location the request is coming from, and redirect to a blocked route based on that location. The project will use no framework, and have minimal dependencies.

After completing this guide you will have learnt how to use:

  • Edge Middleware with Vercel CLI
  • Use the @vercel/edge package and its geolocation helper function
  • Update a request to a new url based on the location
  • Redirect to a blocked route based on the location

Begin by adding the @vercel/edge package to your project with:


npm i @vercel/edge

Installing @vercel/edge using the npm command.

Next, add a middleware.js file at the root of your project's 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 JavaScript.

For this quickstart, you should also add some new helper files: index.html, and blocked.html. 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.

index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vercel Edge Middleware</title>
  </head>
  <main>
    <h1>Hello! Welcome to The Edge!</h1>
  </main>
</html>
blocked.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vercel Edge Middleware</title>
  </head>
  <main>
    <h1>You are blocked from viewing this page</h1>
  </main>
</html>

The following example uses the @vercel/edge package to import a helper geolocation function. See the Edge Middleware API docs for more information on this package.

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.

Copy and paste the following into your middleware function:

middleware.js
import { geolocation } from '@vercel/edge';

const BLOCKED_COUNTRY = 'US';

export const config = {
  // Only run the middleware on the home route
  matcher: '/',
};

export default function middleware(request) {
  const url = new URL(request.url);

  const { country } = geolocation(request);
  // You can also get the country using dot notation on the function
  // const country = geolocation(request).country;

  if (country === BLOCKED_COUNTRY) {
    url.pathname = '/blocked.html';
  } else {
    url.pathname = 'index.html';
  }

  // Return a new redirect response
  return Response.redirect(url);
}

To test your Middleware, use the Vercel CLI to deploy your project with vercel deploy.

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.

You have created a basic project and deployed Edge Middleware. Based on the incoming request's location, you have redirected the request to a blocked page.

  • Edge Middleware runs before the cache
  • You can use a custom matcher config to only trigger the middleware in specific routes
  • You can use the @vercel/edge package to import helper functions
  • 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.