Unverified Commit 129052dc authored by Kiko Beats's avatar Kiko Beats Committed by GitHub

Edge Functions: deprecate access to `request.page` (#37349)

It uses `URLSearchParams` to have the same behavior.

closes https://github.com/vercel/next.js/issues/34521
parent 1420dd9a
...@@ -669,6 +669,10 @@ ...@@ -669,6 +669,10 @@
{ {
"title": "returning-response-body-in-middleware", "title": "returning-response-body-in-middleware",
"path": "/errors/returning-response-body-in-middleware.md" "path": "/errors/returning-response-body-in-middleware.md"
},
{
"title": "middleware-request-page.md",
"path": "/errors/middleware-request-page.md"
} }
] ]
} }
......
# Deprecated page into Middleware API
#### Why This Error Occurred
Your application is interacting with `request.page`, and it's being deprecated.
```typescript
// 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/en-US/docs/Web/API/URLPattern) instead to have the same behavior:
```typescript
// 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)
}
}
```
import type { NextMiddleware, RequestData, FetchEventResult } from './types' import type { NextMiddleware, RequestData, FetchEventResult } from './types'
import type { RequestInit } from './spec-extension/request' import type { RequestInit } from './spec-extension/request'
import { DeprecationError } from './error' import { DeprecationSignatureError } from './error'
import { fromNodeHeaders } from './utils' import { fromNodeHeaders } from './utils'
import { NextFetchEvent } from './spec-extension/fetch-event' import { NextFetchEvent } from './spec-extension/fetch-event'
import { NextRequest } from './spec-extension/request' import { NextRequest } from './spec-extension/request'
...@@ -23,7 +23,6 @@ export async function adapter(params: { ...@@ -23,7 +23,6 @@ export async function adapter(params: {
ip: params.request.ip, ip: params.request.ip,
method: params.request.method, method: params.request.method,
nextConfig: params.request.nextConfig, nextConfig: params.request.nextConfig,
page: params.request.page,
}, },
}) })
...@@ -97,14 +96,14 @@ class NextRequestHint extends NextRequest { ...@@ -97,14 +96,14 @@ class NextRequestHint extends NextRequest {
} }
get request() { get request() {
throw new DeprecationError({ page: this.sourcePage }) throw new DeprecationSignatureError({ page: this.sourcePage })
} }
respondWith() { respondWith() {
throw new DeprecationError({ page: this.sourcePage }) throw new DeprecationSignatureError({ page: this.sourcePage })
} }
waitUntil() { waitUntil() {
throw new DeprecationError({ page: this.sourcePage }) throw new DeprecationSignatureError({ page: this.sourcePage })
} }
} }
export class DeprecationError extends Error { export class DeprecationSignatureError extends Error {
constructor({ page }: { page: string }) { constructor({ page }: { page: string }) {
super(`The middleware "${page}" accepts an async API directly with the form: super(`The middleware "${page}" accepts an async API directly with the form:
...@@ -10,3 +10,11 @@ export class DeprecationError extends Error { ...@@ -10,3 +10,11 @@ export class DeprecationError extends Error {
`) `)
} }
} }
export class DeprecationPageError extends Error {
constructor() {
super(`The request.page has been deprecated in favour of URLPattern.
Read more: https://nextjs.org/docs/messages/middleware-request-page
`)
}
}
import { DeprecationError } from '../error' import { DeprecationSignatureError } from '../error'
import { NextRequest } from './request' import { NextRequest } from './request'
const responseSymbol = Symbol('response') const responseSymbol = Symbol('response')
...@@ -42,7 +42,7 @@ export class NextFetchEvent extends FetchEvent { ...@@ -42,7 +42,7 @@ export class NextFetchEvent extends FetchEvent {
* Read more: https://nextjs.org/docs/messages/middleware-new-signature * Read more: https://nextjs.org/docs/messages/middleware-new-signature
*/ */
get request() { get request() {
throw new DeprecationError({ throw new DeprecationSignatureError({
page: this.sourcePage, page: this.sourcePage,
}) })
} }
...@@ -53,7 +53,7 @@ export class NextFetchEvent extends FetchEvent { ...@@ -53,7 +53,7 @@ export class NextFetchEvent extends FetchEvent {
* Read more: https://nextjs.org/docs/messages/middleware-new-signature * Read more: https://nextjs.org/docs/messages/middleware-new-signature
*/ */
respondWith() { respondWith() {
throw new DeprecationError({ throw new DeprecationSignatureError({
page: this.sourcePage, page: this.sourcePage,
}) })
} }
......
...@@ -4,6 +4,7 @@ import { NextURL } from '../next-url' ...@@ -4,6 +4,7 @@ import { NextURL } from '../next-url'
import { isBot } from '../../utils' import { isBot } from '../../utils'
import { toNodeHeaders, validateURL } from '../utils' import { toNodeHeaders, validateURL } from '../utils'
import parseua from 'next/dist/compiled/ua-parser-js' import parseua from 'next/dist/compiled/ua-parser-js'
import { DeprecationPageError } from '../error'
import { NextCookies } from './cookies' import { NextCookies } from './cookies'
...@@ -14,7 +15,6 @@ export class NextRequest extends Request { ...@@ -14,7 +15,6 @@ export class NextRequest extends Request {
cookies: NextCookies cookies: NextCookies
geo: RequestData['geo'] geo: RequestData['geo']
ip?: string ip?: string
page?: { name?: string; params?: { [key: string]: string | string[] } }
ua?: UserAgent | null ua?: UserAgent | null
url: NextURL url: NextURL
} }
...@@ -27,7 +27,6 @@ export class NextRequest extends Request { ...@@ -27,7 +27,6 @@ export class NextRequest extends Request {
cookies: new NextCookies(this), cookies: new NextCookies(this),
geo: init.geo || {}, geo: init.geo || {},
ip: init.ip, ip: init.ip,
page: init.page,
url: new NextURL(url, { url: new NextURL(url, {
headers: toNodeHeaders(this.headers), headers: toNodeHeaders(this.headers),
nextConfig: init.nextConfig, nextConfig: init.nextConfig,
...@@ -56,10 +55,7 @@ export class NextRequest extends Request { ...@@ -56,10 +55,7 @@ export class NextRequest extends Request {
} }
public get page() { public get page() {
return { throw new DeprecationPageError()
name: this[INTERNALS].page?.name,
params: this[INTERNALS].page?.params,
}
} }
public get ua() { public get ua() {
...@@ -98,10 +94,6 @@ export interface RequestInit extends globalThis.RequestInit { ...@@ -98,10 +94,6 @@ export interface RequestInit extends globalThis.RequestInit {
i18n?: I18NConfig | null i18n?: I18NConfig | null
trailingSlash?: boolean trailingSlash?: boolean
} }
page?: {
name?: string
params?: { [key: string]: string | string[] }
}
} }
interface UserAgent { interface UserAgent {
......
/* global globalThis */ /* global globalThis, URLPattern */
import { NextRequest, NextResponse } from 'next/server' import { NextRequest, NextResponse } from 'next/server'
import magicValue from 'shared-package' import magicValue from 'shared-package'
const PATTERNS = [
[
new URLPattern({ pathname: '/:locale/:id' }),
({ pathname }) => ({
pathname: '/:locale/:id',
params: pathname.groups,
}),
],
[
new URLPattern({ pathname: '/:id' }),
({ pathname }) => ({
pathname: '/:id',
params: 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 async function middleware(request) { export async function middleware(request) {
const url = request.nextUrl const url = request.nextUrl
...@@ -151,8 +182,8 @@ export async function middleware(request) { ...@@ -151,8 +182,8 @@ export async function middleware(request) {
headers: { headers: {
'req-url-basepath': request.nextUrl.basePath, 'req-url-basepath': request.nextUrl.basePath,
'req-url-pathname': request.nextUrl.pathname, 'req-url-pathname': request.nextUrl.pathname,
'req-url-params': JSON.stringify(request.page.params), 'req-url-params':
'req-url-page': request.page.name, url.pathname !== '/static' ? JSON.stringify(params(request.url)) : '{}',
'req-url-query': request.nextUrl.searchParams.get('foo'), 'req-url-query': request.nextUrl.searchParams.get('foo'),
'req-url-locale': request.nextUrl.locale, 'req-url-locale': request.nextUrl.locale,
}, },
......
...@@ -205,9 +205,14 @@ function tests(context, locale = '') { ...@@ -205,9 +205,14 @@ function tests(context, locale = '') {
it(`should validate & parse request url from any route`, async () => { it(`should validate & parse request url from any route`, async () => {
const res = await fetchViaHTTP(context.appPort, `${locale}/static`) const res = await fetchViaHTTP(context.appPort, `${locale}/static`)
expect(res.headers.get('req-url-basepath')).toBe('') expect(res.headers.get('req-url-basepath')).toBe('')
expect(res.headers.get('req-url-pathname')).toBe('/static') expect(res.headers.get('req-url-pathname')).toBe('/static')
expect(res.headers.get('req-url-params')).not.toBe('{}')
const { pathname, params } = JSON.parse(res.headers.get('req-url-params'))
expect(pathname).toBe(undefined)
expect(params).toEqual(undefined)
expect(res.headers.get('req-url-query')).not.toBe('bar') expect(res.headers.get('req-url-query')).not.toBe('bar')
if (locale !== '') { if (locale !== '') {
expect(res.headers.get('req-url-locale')).toBe(locale.slice(1)) expect(res.headers.get('req-url-locale')).toBe(locale.slice(1))
...@@ -216,10 +221,14 @@ function tests(context, locale = '') { ...@@ -216,10 +221,14 @@ function tests(context, locale = '') {
it(`should validate & parse request url from a dynamic route with params`, async () => { it(`should validate & parse request url from a dynamic route with params`, async () => {
const res = await fetchViaHTTP(context.appPort, `/fr/1`) const res = await fetchViaHTTP(context.appPort, `/fr/1`)
expect(res.headers.get('req-url-basepath')).toBe('') expect(res.headers.get('req-url-basepath')).toBe('')
expect(res.headers.get('req-url-pathname')).toBe('/1') expect(res.headers.get('req-url-pathname')).toBe('/1')
expect(res.headers.get('req-url-params')).toBe('{"id":"1"}')
expect(res.headers.get('req-url-page')).toBe('/[id]') const { pathname, params } = JSON.parse(res.headers.get('req-url-params'))
expect(pathname).toBe('/:locale/:id')
expect(params).toEqual({ locale: 'fr', id: '1' })
expect(res.headers.get('req-url-query')).not.toBe('bar') expect(res.headers.get('req-url-query')).not.toBe('bar')
expect(res.headers.get('req-url-locale')).toBe('fr') expect(res.headers.get('req-url-locale')).toBe('fr')
}) })
...@@ -227,9 +236,11 @@ function tests(context, locale = '') { ...@@ -227,9 +236,11 @@ function tests(context, locale = '') {
it(`should validate & parse request url from a dynamic route with params and no query`, async () => { it(`should validate & parse request url from a dynamic route with params and no query`, async () => {
const res = await fetchViaHTTP(context.appPort, `/fr/abc123`) const res = await fetchViaHTTP(context.appPort, `/fr/abc123`)
expect(res.headers.get('req-url-basepath')).toBe('') expect(res.headers.get('req-url-basepath')).toBe('')
expect(res.headers.get('req-url-pathname')).toBe('/abc123')
expect(res.headers.get('req-url-params')).toBe('{"id":"abc123"}') const { pathname, params } = JSON.parse(res.headers.get('req-url-params'))
expect(res.headers.get('req-url-page')).toBe('/[id]') expect(pathname).toBe('/:locale/:id')
expect(params).toEqual({ locale: 'fr', id: 'abc123' })
expect(res.headers.get('req-url-query')).not.toBe('bar') expect(res.headers.get('req-url-query')).not.toBe('bar')
expect(res.headers.get('req-url-locale')).toBe('fr') expect(res.headers.get('req-url-locale')).toBe('fr')
}) })
...@@ -237,9 +248,12 @@ function tests(context, locale = '') { ...@@ -237,9 +248,12 @@ function tests(context, locale = '') {
it(`should validate & parse request url from a dynamic route with params and query`, async () => { it(`should validate & parse request url from a dynamic route with params and query`, async () => {
const res = await fetchViaHTTP(context.appPort, `/abc123?foo=bar`) const res = await fetchViaHTTP(context.appPort, `/abc123?foo=bar`)
expect(res.headers.get('req-url-basepath')).toBe('') expect(res.headers.get('req-url-basepath')).toBe('')
expect(res.headers.get('req-url-pathname')).toBe('/abc123')
expect(res.headers.get('req-url-params')).toBe('{"id":"abc123"}') const { pathname, params } = JSON.parse(res.headers.get('req-url-params'))
expect(res.headers.get('req-url-page')).toBe('/[id]')
expect(pathname).toBe('/:id')
expect(params).toEqual({ id: 'abc123' })
expect(res.headers.get('req-url-query')).toBe('bar') expect(res.headers.get('req-url-query')).toBe('bar')
expect(res.headers.get('req-url-locale')).toBe('en') expect(res.headers.get('req-url-locale')).toBe('en')
}) })
......
...@@ -7,8 +7,6 @@ export const middleware: NextMiddleware = function (request) { ...@@ -7,8 +7,6 @@ export const middleware: NextMiddleware = function (request) {
data: 'hello from middleware', data: 'hello from middleware',
'req-url-basepath': request.nextUrl.basePath, 'req-url-basepath': request.nextUrl.basePath,
'req-url-pathname': request.nextUrl.pathname, 'req-url-pathname': request.nextUrl.pathname,
'req-url-params': JSON.stringify(request.page.params) || '',
'req-url-page': request.page.name || '',
'req-url-query': request.nextUrl.searchParams.get('foo') || '', 'req-url-query': request.nextUrl.searchParams.get('foo') || '',
'req-url-locale': request.nextUrl.locale, 'req-url-locale': request.nextUrl.locale,
}, },
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment