Warning: Edge Functions are currently in Beta . The API might change as we look to continually make improvements.

Edge Functions allow you to quickly deliver personalized content to your site's users. When a user makes a request to your site, the Edge Function uses Middleware to handle the request. Middleware allows you to run code to process or modify the response by rewriting, redirecting, or adding headers. Mostly importantly, Edge Functions run close to your visitor's location for the fastest responses.

In this guide, you'll learn how to get started with Edge Functions by using Middleware within a Next.js app. When you run Middleware on an app that is deployed to Vercel, it is automatically deployed as an Edge Function.

Prerequisites

  • An existing Vercel app. If you haven't already deployed your app, visit the tutorial
  • Currently Edge Functions only support Next.js apps. Ensure that your app is using the most recent version of Next.js by installing the latest version of next:
npm install next@latest

Create your first Edge Function

Create a _middleware.js file in the pages directory of your project

When you add this file to a project that is deployed to Vercel, it's automatically deployed as an Edge Function. You can add more than one _middleware file to your project, for example for API routes or for various static pages, provided they are under the pages directory.

You can learn more about the Middleware running order in the Middleware page.

Add Middleware code

Copy and paste one of the following functions into your middleware:

import { NextRequest } from 'next/server';

export function middleware(request) {
  const country = request.geo.country || 'US';

  return new Response(`Hello, World. I'm in ${country}`);
}

Test your function

Run your function locally by using npm run dev or yarn dev to start the development server. Open the development server, usually at http://localhost:3000.

Note: When you're working locally with the `geo` property, your IP address is `127.0.0.1` and so the output will fall back to the default.

Commit and push the change to your app

Once you're happy with your changes, you should push them to the remote repository. Because Vercel makes a new deployment for each each push by default, your Edge Function will automatically go live.

Check Function logs

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:

Edge Functions Logs view.