# 中间件

中间件允许您在配置之上使用代码。这为你在Next.js中提供了充分的灵活性,因为你可以在请求完成之前运行代码。根据用户传入的请求,您可以通过重写、重定向、添加报头甚至流式HTML来修改响应。

# Usage

  • Install the latest version of Next.js:
npm install next@latest

  • Then, create a _middleware.tsfile under your /pagesdirectory.

  • Finally, export a middleware function from the _middleware.tsfile.

// pages/_middleware.ts

import type { NextFetchEvent, NextRequest } from 'next/server'

export function middleware(req: NextRequest, ev: NextFetchEvent) {
  return new Response('Hello, world!')
}

In this example, we use the standard Web API Response (MDN ).

# Examples

Middleware can be used for anything that shares logic for a set of pages, including:

  • Authentication
  • Bot protection
  • Redirects and rewrites
  • Handling unsupported browsers
  • Feature flags and A/B tests
  • Server-side analytics
  • Advanced i18n routing requirements
  • Logging

# Execution Order

If your Middleware is created in /pages/_middleware.ts, it will run on all routes within the /pagesdirectory. The below example assumes you have about.tsxand teams.tsxroutes.

- package.json
- /pages
    _middleware.ts # Will run on all routes under /pages
    index.tsx
    about.tsx
    teams.tsx

If you dohave sub-directories with nested routes, Middleware will run from the top down. For example, if you have /pages/about/_middleware.tsand /pages/about/team/_middleware.ts, /aboutwill run first and then /about/team. The below example shows how this works with a nested routing structure.

- package.json
- /pages
    index.tsx
    - /about
      _middleware.ts # Will run first
      about.tsx
      - /teams
        _middleware.ts # Will run second
        teams.tsx

Middleware runs directly after redirectsand headers, before the first filesystem lookup. This excludes /_nextfiles.

# Deployment

Middleware uses a strict runtime that supports standard Web APIs like fetch. This works out of the box using next start, as well as on Edge platforms like Vercel, which use Edge Functions .

Middleware API ReferenceLearn more about the supported APIs for Middleware. Edge RuntimeLearn more about the supported Web APIs available.

Last Updated: 5/13/2023, 8:55:38 PM