• Product Introduction
  • Quick Start
    • Importing a Git Repository
    • Starting From a Template
    • Direct Upload
    • Start with AI
  • Framework Guide
    • Frontends
      • Vite
      • React
      • Vue
      • Other Frameworks
    • Backends
    • Full-stack
      • Next.js
      • Nuxt
      • Astro
      • React Router
      • SvelteKit
    • Custom 404 Page
  • Project Guide
    • Project Management
    • edgeone.json
    • Configuring Cache
    • Error Codes
  • Build Guide
  • Deployment Guide
    • Overview
    • Create Deploys
    • Manage Deploys
    • Deploy Button
    • Using Github Actions
    • Using CNB Plugin
    • Using IDE PlugIn
    • Using CodeBuddy IDE
  • Domain Management
    • Overview
    • Custom Domain
    • HTTPS Configuration
      • Overview
      • Apply for Free Certificate
      • Using Managed SSL Certificate
    • Configure DNS CNAME Record
  • Observability
    • Overview
    • Metric Analysis
    • Log Analysis
  • Pages Functions
    • Overview
    • Edge Functions
    • Cloud Functions
      • Overview
      • Node Functions
  • Middleware
  • KV Storage
  • Edge AI
  • API Token
  • EdgeOne CLI
  • Pages MCP
  • Message Notification
  • Integration Guide
    • AI
      • Dialogue Large Models Integration
      • Large Models for Images Integration
    • Database
      • Supabase Integration
      • Pages KV Integration
    • Ecommerce
      • Shopify Integration
      • WooCommerce Integration
    • Payment
      • Stripe Integration
      • Integrating Paddle
    • CMS
      • WordPress Integration
      • Contentful Integration
      • Sanity Integration
      • Payload Integration
    • Authentication
      • Supabase Integration
      • Clerk Integration
  • Best Practices
    • Using General Large Model to Quickly Build AI Application
    • Use the DeepSeek model to quickly build a conversational AI site
    • Building an Ecommerce Platform with Shopify
    • Building a SaaS Site Using Supabase and Stripe
    • Building a Company Brand Site Quickly
    • How to Quickly Build a Blog Site
  • Migration Guides
    • Migrating from Vercel to EdgeOne Pages
    • Migrating from Cloudflare Pages to EdgeOne Pages
    • Migrating from Netlify to EdgeOne Pages
  • Troubleshooting
  • FAQs
  • Contact Us
  • Release Notes

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.js
export function middleware(context) {
const { request, next, redirect, rewrite } = context;
// Request direct pass-through
return 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);
// Redirect
if (url.pathname === '/protected') {
return redirect('/login', 308);
}
}

Rewrite URL

export function middleware(context) {
const { request, rewrite } = context;
const url = new URL(request.url);
// Rewrite
if (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 server
return context.next({
headers: {
'x-custom-header': 'middleware-added',
'x-request-id': Math.random(),
}
});
}

Return Directly Response

export function middleware(context) {
// Return directly response
return 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.js
export function middleware(context) {
// Middleware logic
return context.next();
}

// Configure the route matching rule
export 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 service
edgeone 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.

ai-agent
You can ask me like
How to Get Started with EdgeOne Pages?