• 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
      • TanStack Start
      • Vike
    • 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 Gitlab CI/CD
    • 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.

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 authentication, IP/geographical restrictions, 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, region, 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:
Property
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
geo
GeoProperties
Client request location information
clientIp
string
Client IP address
GeoProperties specific properties are as follows:
Property
Type
Description
Example Value
asn
number
ASN
132203
countryName
string
Country name
Singapore
countryCodeAlpha2
string
Country's ISO-3166 alpha2 code
SG
countryCodeAlpha3
string
Country's ISO-3166 alpha3 code
SGP
countryCodeNumeric
string
Country's ISO-3166 numeric code
702
regionName
string
Region name
-
regionCode
string
Area code
AA-AA
cityName
string
City name
Singapore
latitude
number
Latitude
1.29027
longitude
number
Longitude
103.851959
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?