Routing Middleware: JS Reference
Use this reference to write Routing Middleware in TypeScript or JavaScript. For path matching and limits, see the Routing Middleware overview.
You can tell Edgenivo where your Routing Middleware is in two ways.
Set proxy.entrypoint in vercel.json to a .ts or .js file, such as proxy.ts or src/proxy.ts:
{
"$schema": "https://openapi.vercel.sh/vercel.json",
"proxy": {
"entrypoint": "proxy.ts"
}
}Name the file middleware.ts and place it at the root of your project, at the same level as your package.json file. The default runtime is Node.js. See Specify runtime.
In Next.js, place the proxy.ts file at the same level as your app or pages directory, even if you use a src directory.
The Routing Middleware must be a default export, with the function being named anything you like. For example, you can name it router, middleware, or any other name that makes sense for your application.
export default function proxy(request: Request) {
return new Response('Hello from your Middleware!');
}export default function proxy(request) {
return new Response('Hello from your Middleware!');
}Routing 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.
You can also use the runtime option to specify which runtime you would like to use. The default is nodejs.
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 Routing Middleware when it matches specific paths.
Export a config object with a matcher property to choose which paths run your Routing Middleware. The matcher accepts a single path or an array of paths:
export const config = {
matcher: ['/about/:path*', '/dashboard/:path*'],
};If you configure your entrypoint with proxy, set the matcher here or in proxy.matcher. See path matching for the matcher syntax, including regex support.
import { rewrite } from '@vercel/functions';
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/functions package.
To set the runtime explicitly, update the runtime option as follows:
export const config = {
runtime: 'nodejs',
};To use the Bun runtime with Routing Middleware, set the bunVersion property in your vercel.json file as well as using the runtime config shown above to nodejs:
{
"$schema": "https://openapi.vercel.sh/vercel.json",
"bunVersion": "1.4.x"
}| Property | Type | Description |
|---|---|---|
matcher | string / string[] | A string or array of strings that define the paths the Middleware should be run on |
runtime | string (nodejs) | A string that defines the Middleware runtime and defaults to nodejs |
The Routing 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 |
Routing Middleware comes with built in helpers that are based on the native FetchEvent, Response, and Request objects.
See the section on Routing Middleware helpers 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));
}// config with custom matcher
export const config = {
matcher: '/about/:path*',
};
export default function middleware(request) {
return Response.redirect(new URL('/about-2', request.url));
}// 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));
}// config with custom matcher
export const config = {
matcher: '/about/:path*',
};
export default function middleware(request) {
return Response.redirect(new URL('/about-2', request.url));
}// 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));
}// config with custom matcher
export const config = {
matcher: '/about/:path*',
};
export default function middleware(request) {
return Response.redirect(new URL('/about-2', request.url));
}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 |
To learn more about the NextRequest object and its properties, visit the Next.js documentation.
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
import type { NextFetchEvent } from 'next/server';
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: NextFetchEvent) {
context.waitUntil(getProduct().then((json) => console.log({ json })));
return new Response(JSON.stringify({ hello: 'world' }), {
status: 200,
headers: { 'content-type': 'application/json' },
});
}export const config = {
matcher: '/',
};
const wait = (ms) => 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, context) {
context.waitUntil(getProduct().then((json) => console.log({ json })));
return new Response(JSON.stringify({ hello: 'world' }), {
status: 200,
headers: { 'content-type': 'application/json' },
});
}import type { NextFetchEvent } from 'next/server';
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: NextFetchEvent) {
context.waitUntil(getProduct().then((json) => console.log({ json })));
return new Response(JSON.stringify({ hello: 'world' }), {
status: 200,
headers: { 'content-type': 'application/json' },
});
}import { NextResponse } from 'next/server';
export const config = {
matcher: '/',
};
const wait = (ms) => 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();
}
export default function middleware(request, context) {
context.waitUntil(getAlbum().then((json) => console.log({ json })));
return new NextResponse(JSON.stringify({ hello: 'world' }), {
status: 200,
headers: { 'content-type': 'application/json' },
});
}import type { RequestContext } from '@vercel/functions';
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' },
},
);
}export const config = {
matcher: '/',
};
const wait = (ms) => 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, context) {
context.waitUntil(getProduct().then((json) => console.log({ json })));
return Response.json(
{ hello: 'world' },
{
status: 200,
headers: { 'content-type': 'application/json' },
},
);
}| 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 Edgenivo-specific helper methods to access a request's geolocation, IP address, and more when deploying Middleware on Edgenivo.
You can access these helper methods with the request and response objects in your middleware handler method.
To read a request's location, see geolocation headers.
The ip object returns the IP address of the request from the headers, or undefined.
import { ipAddress } from '@vercel/functions';
import { next } from '@vercel/functions';
export default function middleware(request: Request) {
const ip = ipAddress(request);
return next({
headers: { 'x-your-ip-address': ip || 'unknown' },
});
}import { ipAddress } from '@vercel/functions';
import { next } from '@vercel/functions';
export default function middleware(request) {
const ip = ipAddress(request);
return next({
headers: { 'x-your-ip-address': ip || 'unknown' },
});
}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/functions';
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 a Edgenivo 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();
}export default function handler(request, context) {
context.waitUntil(getAlbum().then((json) => console.log({ json })));
return new Response(
`Hello there, from ${request.url} I'm a Edgenivo Function!`,
);
}
export const config = {
matcher: '/',
};
const wait = (ms) => 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();
}The NextResponse.rewrite() helper returns a response that rewrites the request to a different URL.
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
// Trigger this middleware to run on the `/about` route
export const config = {
matcher: '/about',
};
export default function middleware(request: NextRequest) {
// Rewrite to URL
return NextResponse.rewrite('/about-2');
}import { NextResponse } from 'next/server';
// Trigger this middleware to run on the `/about` route
export const config = {
matcher: '/about',
};
export default function middleware(request) {
// Rewrite to URL
return NextResponse.rewrite('/about-2');
}import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
// Trigger this middleware to run on the `/about` route
export const config = {
matcher: '/about',
};
export default function middleware(request: NextRequest) {
// Rewrite to URL
return NextResponse.rewrite('/about-2');
}import { NextResponse } from 'next/server';
// Trigger this middleware to run on the `/about` route
export const config = {
matcher: '/about',
};
export default function middleware(request) {
// Rewrite to URL
return NextResponse.rewrite('/about-2');
}import { rewrite } from '@vercel/functions';
// 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));
}import { rewrite } from '@vercel/functions';
// Trigger this middleware to run on the `/about` route
export const config = {
matcher: '/about',
};
export default function middleware(request) {
return rewrite(new URL('/about-2', request.url));
}The NextResponse.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 Routing Middleware chain:
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
// Clone the request headers and set a new header `x-hello-from-middleware1`
const requestHeaders = new Headers(request.headers);
requestHeaders.set('x-hello-from-middleware1', 'hello');
// You can also set request headers in NextResponse.next
const response = NextResponse.next({
request: {
// New request headers
headers: requestHeaders,
},
});
// Set a new response header `x-hello-from-middleware2`
response.headers.set('x-hello-from-middleware2', 'hello');
return response;
}import { NextResponse } from 'next/server'
export function middleware(request) {
// Clone the request headers and set a new header `x-hello-from-middleware1`
const requestHeaders = new Headers(request.headers)
requestHeaders.set('x-hello-from-middleware1', 'hello')
// You can also set request headers in NextResponse.next
const response = NextResponse.next({
request: {
// New request headers
headers: requestHeaders,
},
})
// Set a new response header `x-hello-from-middleware2`
response.headers.set('x-hello-from-middleware2', 'hello')
return response
}import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
// Clone the request headers and set a new header `x-hello-from-middleware1`
const requestHeaders = new Headers(request.headers);
requestHeaders.set('x-hello-from-middleware1', 'hello');
// You can also set request headers in NextResponse.next
const response = NextResponse.next({
request: {
// New request headers
headers: requestHeaders,
},
});
// Set a new response header `x-hello-from-middleware2`
response.headers.set('x-hello-from-middleware2', 'hello');
return response;
}import { NextResponse } from 'next/server';
export function middleware(request) {
// Clone the request headers and set a new header `x-hello-from-middleware1`
const requestHeaders = new Headers(request.headers);
requestHeaders.set('x-hello-from-middleware1', 'hello');
// You can also set request headers in NextResponse.next
const response = NextResponse.next({
request: {
// New request headers
headers: requestHeaders,
},
});
// Set a new response header `x-hello-from-middleware2`
response.headers.set('x-hello-from-middleware2', 'hello');
return response;
}import { next } from '@vercel/functions';
export default function middleware(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',
},
});
}import { next } from '@vercel/functions';
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 { NextResponse } from 'next/server';
export default function middleware() {
return NextResponse.next();
}import { NextResponse } from 'next/server';
export default function middleware() {
return NextResponse.next();
}import { NextResponse } from 'next/server';
export default function middleware() {
return NextResponse.next();
}import { NextResponse } from 'next/server';
export default function middleware() {
return NextResponse.next();
}import { next } from '@vercel/functions';
export default function middleware() {
return next();
}import { next } from '@vercel/functions';
export default function middleware() {
return next();
}Was this helpful?