Skip to content

Commit

Permalink
docs: Add JS/TS code switchers to Middleware (#54726)
Browse files Browse the repository at this point in the history
In case a user needs a `js` code
  • Loading branch information
0xScratch authored Aug 31, 2023
1 parent 44509f6 commit 4f0b715
Showing 1 changed file with 30 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand All @@ -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:
Expand Down Expand Up @@ -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'

Expand All @@ -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:
Expand Down

0 comments on commit 4f0b715

Please sign in to comment.