docs: Add JS/TS code switchers to Middleware (#54726)
In case a user needs a `js` code
This commit is contained in:
parent
44509f690a
commit
4f0b7156a4
1 changed files with 30 additions and 2 deletions
|
@ -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:
|
||||
|
|
Loading…
Reference in a new issue