diff --git a/docs/02-app/01-building-your-application/01-routing/11-middleware.mdx b/docs/02-app/01-building-your-application/01-routing/11-middleware.mdx index f5fad4ff8e..5942e1202f 100644 --- a/docs/02-app/01-building-your-application/01-routing/11-middleware.mdx +++ b/docs/02-app/01-building-your-application/01-routing/11-middleware.mdx @@ -15,7 +15,7 @@ Use the file `middleware.ts` (or `.js`) in the root of your project to define Mi ## Example -```ts filename="middleware.ts" +```ts filename="middleware.ts" switcher import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' @@ -30,6 +30,20 @@ export const config = { } ``` +```js filename="middleware.js" switcher +import { NextResponse } from 'next/server' + +// This function can be marked `async` if using `await` inside +export function middleware(request) { + return NextResponse.redirect(new URL('/home', request.url)) +} + +// See "Matching Paths" below to learn more +export const config = { + matcher: '/about/:path*', +} +``` + ## Matching Paths Middleware will be invoked for **every route in your project**. The following is the execution order: @@ -98,7 +112,7 @@ Read more details on [path-to-regexp](https://github.com/pillarjs/path-to-regexp ### Conditional Statements -```ts filename="middleware.ts" +```ts filename="middleware.ts" switcher import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' @@ -113,6 +127,20 @@ export function middleware(request: NextRequest) { } ``` +```js filename="middleware.js" switcher +import { NextResponse } from 'next/server' + +export function middleware(request) { + if (request.nextUrl.pathname.startsWith('/about')) { + return NextResponse.rewrite(new URL('/about-2', request.url)) + } + + if (request.nextUrl.pathname.startsWith('/dashboard')) { + return NextResponse.rewrite(new URL('/dashboard/user', request.url)) + } +} +``` + ## NextResponse The `NextResponse` API allows you to: