rsnext/errors/middleware-request-page.mdx
Michael Novotny fe797c1074
Updates Mozilla links to not include language preference (#55326)
Internal suggestion to remove `en-US` from Mozilla urls since MDN is
available in multiple languages nowadays it will automatically redirect
to the viewer’s language preference.

Closes
[DX-2076](https://linear.app/vercel/issue/DX-2076/make-external-mozilla-links-language-agnostic-in-nextjs-docs)
2023-09-13 11:06:29 -05:00

61 lines
1.5 KiB
Text

---
title: Removed page from Middleware API
---
## Why This Error Occurred
Your application is interacting with `request.page` which has been deprecated.
```ts filename="middleware.ts"
import { NextRequest, NextResponse } from 'next/server'
export function middleware(request: NextRequest) {
const { params } = event.request.page
const { locale, slug } = params
if (locale && slug) {
const { search, protocol, host } = request.nextUrl
const url = new URL(`${protocol}//${locale}.${host}/${slug}${search}`)
return NextResponse.redirect(url)
}
}
```
## Possible Ways to Fix It
You can use [URLPattern](https://developer.mozilla.org/docs/Web/API/URLPattern) instead to have the same behavior:
```ts filename="middleware.ts"
import { NextRequest, NextResponse } from 'next/server'
const PATTERNS = [
[
new URLPattern({ pathname: '/:locale/:slug' }),
({ pathname }) => pathname.groups,
],
]
const params = (url) => {
const input = url.split('?')[0]
let result = {}
for (const [pattern, handler] of PATTERNS) {
const patternResult = pattern.exec(input)
if (patternResult !== null && 'pathname' in patternResult) {
result = handler(patternResult)
break
}
}
return result
}
export function middleware(request: NextRequest) {
const { locale, slug } = params(request.url)
if (locale && slug) {
const { search, protocol, host } = request.nextUrl
const url = new URL(`${protocol}//${locale}.${host}/${slug}${search}`)
return NextResponse.redirect(url)
}
}
```