Middleware
Overview
Middleware allows you to intercept user requests before page loading and execute custom logic on EdgeOne edge nodes, processing requests in real time before continuing to forward or return results directly. With the aid of edge computing capability, middleware can perform judgment and processing closer to the user location, thereby reducing origin pull and compute overhead to improve access performance and stability.
Core Capabilities
Middleware currently supports the following four types of request processing:
Redirect URL: Returns 307/308 status codes to redirect users to a new address.
Rewrite URL: Modify the target path of the request without the user's perception.
Modify Request Header: Add or modify the HTTP Header forwarded to the origin server.
Return directly response: Do not access the origin server, but directly return custom content via
new Response().Use Cases
With middleware, you can achieve the following capabilities including but not limited to:
Request rewrite and routing control: Rewrite URL or navigate to different page according to the path, domain name, Header, Cookie, query parameter.
Access control: Perform access interception such as Token verification, IP restriction, and Referer hotlink protection based on request information.
Grayscale release and A/B testing: Divert requests to different versions based on features such as user identity, Cookie, and UA, enabling grayscale release or targeted content delivery.
Return directly: Respond to specific request with custom content (such as 301/302 redirection, JSON response, HTML page), no need to access the origin server.
Note:
Middleware is suitable for lightweight, low-delay request logic processing scenarios. Complex calculations or time-consuming tasks are recommended to be executed in backend services.
Quick Start
1. Create a Middleware File
Create a
middleware.js (or middleware.ts) file in the project root directory, export the middleware function, see the example code below:// middleware.jsexport function middleware(context) {const { request, next, redirect, rewrite } = context;// Request direct pass-throughreturn next();}
2. Context Object
context is the context object passed to the middleware function, containing the following properties:Attribute | Type | Description |
request | Request | Request object of the current Request |
next | (options?: { headers?: Record<string, any> }) => Response | Process the request further, parameters can be input to modify request headers |
redirect | (url: string, status?: number) => Response | Redirect, default status code 307 |
rewrite | (url: string) => Response | Rewrite request path |
Basic usage used as follows:
Redirect URL
export function middleware(context) {const { request, redirect } = context;const url = new URL(request.url);// Redirectif (url.pathname === '/protected') {return redirect('/login', 308);}}
Rewrite URL
export function middleware(context) {const { request, rewrite } = context;const url = new URL(request.url);// Rewriteif (url.pathname === '/old-path') {return rewrite('/new-path'); // relative path// return rewrite('https://www.google.com'); // absolute path}}
Modify Request Header
export function middleware(context) {// Modify the request header forwarded to the origin serverreturn context.next({headers: {'x-custom-header': 'middleware-added','x-request-id': Math.random(),}});}
Return Directly Response
export function middleware(context) {// Return directly responsereturn new Response('Hello World');}
3. Route Matching Configuration
Middleware matches all routes by default. If only specific path is needed to trigger middleware, you can export the
config object and configure the matcher field.// middleware.jsexport function middleware(context) {// Middleware logicreturn context.next();}// Configure the route matching ruleexport const config = {matcher: ['/:path*', // match all routes],};
matcher supports the following configuration modes:Single Path Match
export const config = {matcher: '/about',};
Multi Path Match
export const config = {matcher: ['/api/:path*', '/about/:path*'],};
Regular Expression Match
export const config = {matcher: ['/api/.*', '^/user/\d+$'],};
4. Local Development and Debugging
In the local development environment, you can use the EdgeOne CLI tool to debug middleware, view log output in real time, and verify whether the feature meets expectations.
# Start local development serviceedgeone pages dev
After startup successful, use
console.log() in the middleware code to output debugging information, and the logs will display in real time in the terminal.
