Edge Middleware API Reference
Learn about the Edge runtime and available APIs when working with Edge Middleware. Supported APIs include Network, Encoding, and Web Stream APIs.Edge Middleware runs on the Edge runtime, a runtime built on top of the V8
JavaScript engine. The Edge runtime provides a subset of Web APIs for you to use when creating Middleware. This lightweight API layer is built to be performant and execute code with minimal latency. When writing Middleware, you can use any of the supported APIs from the Edge runtime.
To add Middleware to your app, you need to create a middleware.ts
or middleware.js
file at the same level as your app
or pages
directory (even if you're using a src
directory):
The Middleware function must be a default export as shown below:
export default function customName() {}
Middleware will be invoked for every route in your project. If you only want it to be run on specific paths, you can define those either with a custom matcher config or with conditional statements.
While the config
option is the preferred method, as it does not get invoked on every request, you can also use conditional statements to only run the Middleware when it matches specific paths.
To decide which route the Middleware should be run on, you can use a custom matcher config to filter on specific paths. The matcher property can be used to define either a single path, or using an array syntax for multiple paths.
Edge Middleware runs on every request by default. To run on
specific paths instead, use the matcher
property of
the Middleware config
object. Even when using path
matching, Edge Middleware runs on all
/_next/data/
requests for
getServerSideProps
and
getStaticProps
pages for the sake of consistency. For
more information, review our docs on Edge Middleware
API
as well as the Next.js matcher
docs.
export const config = {
matcher: '/about/:path*',
};
export const config = {
matcher: ['/about/:path*', '/dashboard/:path*'],
};
The matcher config has full regex support for cases such as negative lookaheads or character matching.
To match all request paths except for the ones starting with:
api
(API routes)_next/static
(static files)favicon.ico
(favicon file)
export const config = {
matcher: ['/((?!api|_next/static|favicon.ico).*)'],
};
To match /blog/123
but not /blog/abc
:
export const config = {
matcher: ['/blog/:slug(\\d{1,})'],
};
For help on writing your own regex path matcher, review Path to regexp.
import { rewrite } from '@vercel/edge';
export default function middleware(request: Request) {
const url = new URL(request.url);
if (url.pathname.startsWith('/about')) {
return rewrite(new URL('/about-2', request.url));
}
if (url.pathname.startsWith('/dashboard')) {
return rewrite(new URL('/dashboard/user', request.url));
}
}
See the Helper Methods below for more information on using the @vercel/edge
package.
Property | Type | Description |
---|---|---|
matcher | string / string[] | A string or array of strings that define the paths the Middleware should be run on |
The Edge Middleware signature is made up of two parameters: request
and context
. The request
parameter is an instance of the Request object, and the context
parameter is an object containing the waitUntil
method. Both parameters are optional.
Parameter | Description | Next.js (/app) or (/pages) | Other Frameworks |
---|---|---|---|
request | An instance of the Request object | Request or NextRequest | Request |
context | An extension to the standard Request object | NextFetchEvent | RequestContext |
Edge Middleware comes with built in helpers that are based on the native FetchEvent
, Response
, and Request
objects.
See the section on helpers below for more information.
// config with custom matcher
export const config = {
matcher: '/about/:path*',
};
export default function middleware(request: Request) {
return Response.redirect(new URL('/about-2', request.url));
}
If you're not using a framework, you must either add
"type": "module"
to your
package.json
or change your JavaScript Functions'
file extensions from .js
to
.mjs
The Request
object represents an HTTP request. It is a wrapper around the Fetch API Request
object. When using TypeScript, you do not need to import the Request
object, as it is already available in the global scope.
Property | Type | Description |
---|---|---|
url | string | The URL of the request |
method | string | The HTTP method of the request |
headers | Headers | The headers of the request |
body | ReadableStream | The body of the request |
bodyUsed | boolean | Whether the body has been read |
cache | string | The cache mode of the request |
credentials | string | The credentials mode of the request |
destination | string | The destination of the request |
integrity | string | The integrity of the request |
redirect | string | The redirect mode of the request |
referrer | string | The referrer of the request |
referrerPolicy | string | The referrer policy of the request |
mode | string | The mode of the request |
signal | AbortSignal | The signal of the request |
arrayBuffer | function | Returns a promise that resolves with an ArrayBuffer |
blob | function | Returns a promise that resolves with a Blob |
formData | function | Returns a promise that resolves with a FormData |
json | function | Returns a promise that resolves with a JSON object |
text | function | Returns a promise that resolves with a string |
clone | function | Returns a clone of the request |
The waitUntil()
method is from the ExtendableEvent
interface. It accepts a Promise
as an argument, which will keep the function running until the Promise
resolves.
It can be used to keep the function running after a response has been sent. This is useful when you have an async task that you want to keep running after returning a response.
The example below will:
- Send a response immediately
- Keep the function running for ten seconds
- Fetch a product and log it to the console
Response.json()
is a new addition to the
Response
object and has not yet been added by the
TypeScript team. This means that you will likely see a red error line under
Response.json()
in your editor. You can ignore this
error, as it is a false positive.
import type { RequestContext } from '@vercel/edge';
export const config = {
matcher: '/',
};
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
async function getProduct() {
const res = await fetch('https://api.vercel.app/products/1');
await wait(10000);
return res.json();
}
export default function middleware(request: Request, context: RequestContext) {
context.waitUntil(getProduct().then((json) => console.log({ json })));
return Response.json(
{ hello: 'world' },
{
status: 200,
headers: { 'content-type': 'application/json' },
},
);
}
If you're not using a framework, you must either add
"type": "module"
to your
package.json
or change your JavaScript Functions'
file extensions from .js
to
.mjs
Property | Type | Description |
---|---|---|
waitUntil | (promise: Promise<unknown>): void | Prolongs the execution of the function until the promise passed to waitUntil is resolved |
You can use Vercel-specific helper methods to access a request's geolocation, IP Address, and more when deploying Edge Middleware on Vercel.
These helpers are exclusive to Vercel, and will not work on other providers, even if your app is built with Next.js.
Add the @vercel/edge
package to your project with:
pnpm i @vercel/edge
This helper is also available in Edge Functions .
The geolocation()
helper returns geolocation information for the incoming request. It has the following properties:
Property | Description |
---|---|
city | The city that the request originated from |
country | The country that the request originated from |
latitude | The latitude of the client |
longitude | The longitude of the client |
region | The Edge Network region that received the request |
Each property returns a string
, or undefined
.
import { geolocation } from '@vercel/functions';
const BLOCKED_COUNTRY = 'US';
export const config = {
// Only run the middleware on the home route
matcher: '/',
};
export default function middleware(request: 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);
}
This helper is also available in Edge Functions .
The ipAddress()
helper returns the IP address of the request from the headers, or undefined
.
import { ipAddress } from '@vercel/functions';
import { next } from '@vercel/edge';
export default function middleware(request: Request) {
const ip = ipAddress(request);
return next({
headers: { 'x-your-ip-address': ip || 'unknown' },
});
}
This helper is also available in Edge Functions .
The RequestContext
is an extension of the standard Request
object, which contains the waitUntil
function. The following example works in middleware for all frameworks:
import type { RequestContext } from '@vercel/edge';
export default function handler(request: Request, context: RequestContext) {
context.waitUntil(getAlbum().then((json) => console.log({ json })));
return new Response(`Hello there, from ${request.url} I'm an Edge Function!`);
}
export const config = {
matcher: '/',
};
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
async function getAlbum() {
const res = await fetch('https://jsonplaceholder.typicode.com/albums/1');
await wait(10000);
return res.json();
}
This helper is only available in Edge Middleware.
The rewrite()
helper returns a response that rewrites the request to a different URL.
import { rewrite } from '@vercel/edge';
// Trigger this middleware to run on the `/about` route
export const config = {
matcher: '/about',
};
export default function middleware(request: Request) {
return rewrite(new URL('/about-2', request.url));
}
This helper is only available in Edge Middleware.
The next()
helper returns a Response that instructs the function to continue the middleware chain. It takes the following optional parameters:
Parameter | type | Description |
---|---|---|
headers | Headers[] or Headers | The headers you want to set |
status | number | The status code |
statusText | string | The status text |
The following example adds a custom header, then continues the middleware chain:
pnpm i @vercel/edge
import { next } from '@vercel/edge';
export default function middleware(request: Request) {
// Clone the request headers
const requestHeaders = new Headers(request.headers);
// Set a new header `x-hello-from-middleware1`
requestHeaders.set('x-hello-from-middleware1', 'hello');
// Use the `next()` function to forward the request with modified headers
return next({
request: {
headers: requestHeaders,
},
headers: {
'x-hello-from-middleware2': 'hello',
},
});
}
This no-op example will return a 200 OK
response with no further action:
import { next } from '@vercel/edge';
export default function middleware() {
return next();
}
Was this helpful?