Unverified Commit 649ba863 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

backport: fix dynamic route interception not working when deployed with middleware (#77794)

Backports:

- #64923
parent 10a042cd
import type { ServerRuntime } from '../../types' import type { ServerRuntime } from '../../types'
export const NEXT_QUERY_PARAM_PREFIX = 'nxtP' export const NEXT_QUERY_PARAM_PREFIX = 'nxtP'
export const NEXT_INTERCEPTION_MARKER_PREFIX = 'nxtI'
export const PRERENDER_REVALIDATE_HEADER = 'x-prerender-revalidate' export const PRERENDER_REVALIDATE_HEADER = 'x-prerender-revalidate'
export const PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER = export const PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER =
......
...@@ -72,7 +72,7 @@ import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing- ...@@ -72,7 +72,7 @@ import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path' import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'
import * as Log from '../build/output/log' import * as Log from '../build/output/log'
import escapePathDelimiters from '../shared/lib/router/utils/escape-path-delimiters' import escapePathDelimiters from '../shared/lib/router/utils/escape-path-delimiters'
import { getUtils } from './server-utils' import { getUtils, normalizeNextQueryParam } from './server-utils'
import isError, { getProperError } from '../lib/is-error' import isError, { getProperError } from '../lib/is-error'
import { import {
addRequestMeta, addRequestMeta,
...@@ -113,11 +113,7 @@ import { ...@@ -113,11 +113,7 @@ import {
fromNodeOutgoingHttpHeaders, fromNodeOutgoingHttpHeaders,
toNodeOutgoingHttpHeaders, toNodeOutgoingHttpHeaders,
} from './web/utils' } from './web/utils'
import { import { CACHE_ONE_YEAR, NEXT_CACHE_TAGS_HEADER } from '../lib/constants'
CACHE_ONE_YEAR,
NEXT_CACHE_TAGS_HEADER,
NEXT_QUERY_PARAM_PREFIX,
} from '../lib/constants'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { import {
NextRequestAdapter, NextRequestAdapter,
...@@ -1090,18 +1086,13 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1090,18 +1086,13 @@ export default abstract class Server<ServerOptions extends Options = Options> {
for (const key of Object.keys(parsedUrl.query)) { for (const key of Object.keys(parsedUrl.query)) {
const value = parsedUrl.query[key] const value = parsedUrl.query[key]
if ( normalizeNextQueryParam(key, (normalizedKey) => {
key !== NEXT_QUERY_PARAM_PREFIX && if (!parsedUrl) return // typeguard
key.startsWith(NEXT_QUERY_PARAM_PREFIX)
) {
const normalizedKey = key.substring(
NEXT_QUERY_PARAM_PREFIX.length
)
parsedUrl.query[normalizedKey] = value
parsedUrl.query[normalizedKey] = value
routeParamKeys.add(normalizedKey) routeParamKeys.add(normalizedKey)
delete parsedUrl.query[key] delete parsedUrl.query[key]
} })
} }
// interpolate dynamic params and normalize URL if needed // interpolate dynamic params and normalize URL if needed
......
...@@ -16,7 +16,10 @@ import { ...@@ -16,7 +16,10 @@ import {
} from '../shared/lib/router/utils/prepare-destination' } from '../shared/lib/router/utils/prepare-destination'
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash' import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
import { normalizeRscURL } from '../shared/lib/router/utils/app-paths' import { normalizeRscURL } from '../shared/lib/router/utils/app-paths'
import { NEXT_QUERY_PARAM_PREFIX } from '../lib/constants' import {
NEXT_INTERCEPTION_MARKER_PREFIX,
NEXT_QUERY_PARAM_PREFIX,
} from '../lib/constants'
export function normalizeVercelUrl( export function normalizeVercelUrl(
req: BaseNextRequest, req: BaseNextRequest,
...@@ -32,9 +35,17 @@ export function normalizeVercelUrl( ...@@ -32,9 +35,17 @@ export function normalizeVercelUrl(
delete (_parsedUrl as any).search delete (_parsedUrl as any).search
for (const key of Object.keys(_parsedUrl.query)) { for (const key of Object.keys(_parsedUrl.query)) {
const isNextQueryPrefix =
key !== NEXT_QUERY_PARAM_PREFIX &&
key.startsWith(NEXT_QUERY_PARAM_PREFIX)
const isNextInterceptionMarkerPrefix =
key !== NEXT_INTERCEPTION_MARKER_PREFIX &&
key.startsWith(NEXT_INTERCEPTION_MARKER_PREFIX)
if ( if (
(key !== NEXT_QUERY_PARAM_PREFIX && isNextQueryPrefix ||
key.startsWith(NEXT_QUERY_PARAM_PREFIX)) || isNextInterceptionMarkerPrefix ||
(paramKeys || Object.keys(defaultRouteRegex.groups)).includes(key) (paramKeys || Object.keys(defaultRouteRegex.groups)).includes(key)
) { ) {
delete _parsedUrl.query[key] delete _parsedUrl.query[key]
...@@ -44,6 +55,24 @@ export function normalizeVercelUrl( ...@@ -44,6 +55,24 @@ export function normalizeVercelUrl(
} }
} }
/**
* Normalizes `nxtP` and `nxtI` query param values to remove the prefix.
* This function does not mutate the input key; it calls the provided function
* with the normalized key.
*/
export function normalizeNextQueryParam(
key: string,
onKeyNormalized: (normalizedKey: string) => void
) {
const prefixes = [NEXT_QUERY_PARAM_PREFIX, NEXT_INTERCEPTION_MARKER_PREFIX]
for (const prefix of prefixes) {
if (key !== prefix && key.startsWith(prefix)) {
const normalizedKey = key.substring(prefix.length)
onKeyNormalized(normalizedKey)
}
}
}
export function interpolateDynamicPath( export function interpolateDynamicPath(
pathname: string, pathname: string,
params: ParsedUrlQuery, params: ParsedUrlQuery,
......
...@@ -11,7 +11,6 @@ import { NextURL } from './next-url' ...@@ -11,7 +11,6 @@ import { NextURL } from './next-url'
import { stripInternalSearchParams } from '../internal-utils' import { stripInternalSearchParams } from '../internal-utils'
import { normalizeRscURL } from '../../shared/lib/router/utils/app-paths' import { normalizeRscURL } from '../../shared/lib/router/utils/app-paths'
import { FLIGHT_PARAMETERS } from '../../client/components/app-router-headers' import { FLIGHT_PARAMETERS } from '../../client/components/app-router-headers'
import { NEXT_QUERY_PARAM_PREFIX } from '../../lib/constants'
import { ensureInstrumentationRegistered } from './globals' import { ensureInstrumentationRegistered } from './globals'
import { RequestAsyncStorageWrapper } from '../async-storage/request-async-storage-wrapper' import { RequestAsyncStorageWrapper } from '../async-storage/request-async-storage-wrapper'
import { requestAsyncStorage } from '../../client/components/request-async-storage.external' import { requestAsyncStorage } from '../../client/components/request-async-storage.external'
...@@ -19,6 +18,7 @@ import { getTracer } from '../lib/trace/tracer' ...@@ -19,6 +18,7 @@ import { getTracer } from '../lib/trace/tracer'
import type { TextMapGetter } from 'next/dist/compiled/@opentelemetry/api' import type { TextMapGetter } from 'next/dist/compiled/@opentelemetry/api'
import { MiddlewareSpan } from '../lib/trace/constants' import { MiddlewareSpan } from '../lib/trace/constants'
import { getEdgePreviewProps } from './get-edge-preview-props' import { getEdgePreviewProps } from './get-edge-preview-props'
import { normalizeNextQueryParam } from '../server-utils'
export class NextRequestHint extends NextRequest { export class NextRequestHint extends NextRequest {
sourcePage: string sourcePage: string
...@@ -104,18 +104,14 @@ export async function adapter( ...@@ -104,18 +104,14 @@ export async function adapter(
for (const key of keys) { for (const key of keys) {
const value = requestUrl.searchParams.getAll(key) const value = requestUrl.searchParams.getAll(key)
if ( normalizeNextQueryParam(key, (normalizedKey) => {
key !== NEXT_QUERY_PARAM_PREFIX &&
key.startsWith(NEXT_QUERY_PARAM_PREFIX)
) {
const normalizedKey = key.substring(NEXT_QUERY_PARAM_PREFIX.length)
requestUrl.searchParams.delete(normalizedKey) requestUrl.searchParams.delete(normalizedKey)
for (const val of value) { for (const val of value) {
requestUrl.searchParams.append(normalizedKey, val) requestUrl.searchParams.append(normalizedKey, val)
} }
requestUrl.searchParams.delete(key) requestUrl.searchParams.delete(key)
} })
} }
// Ensure users only see page requests, never data requests. // Ensure users only see page requests, never data requests.
......
import {
NEXT_INTERCEPTION_MARKER_PREFIX,
NEXT_QUERY_PARAM_PREFIX,
} from '../../../../lib/constants'
import { INTERCEPTION_ROUTE_MARKERS } from '../../../../server/future/helpers/interception-routes' import { INTERCEPTION_ROUTE_MARKERS } from '../../../../server/future/helpers/interception-routes'
import { escapeStringRegexp } from '../../escape-regexp' import { escapeStringRegexp } from '../../escape-regexp'
import { removeTrailingSlash } from './remove-trailing-slash' import { removeTrailingSlash } from './remove-trailing-slash'
const NEXT_QUERY_PARAM_PREFIX = 'nxtP'
const NEXT_INTERCEPTION_MARKER_PREFIX = 'nxtI'
export interface Group { export interface Group {
pos: number pos: number
repeat: boolean repeat: boolean
......
export default function Layout({
children,
modal,
}: {
children: React.ReactNode
modal: React.ReactNode
}) {
return (
<>
<div id="children">{children}</div>
<div id="modal">{modal}</div>
</>
)
}
import Link from 'next/link'
export default function Page() {
return (
<div>
<Link href="/foo/p/1">Foo</Link> <Link href="/foo/p/1">Foo</Link>
</div>
)
}
export default function Layout(props: { children: React.ReactNode }) {
return (
<html>
<body>
<div>{props.children}</div>
</body>
</html>
)
}
import { createNextDescribe } from 'e2e-utils'
import { check } from 'next-test-utils'
createNextDescribe(
'interception-dynamic-segment-middleware',
{
files: __dirname,
},
({ next }) => {
it('should work when interception route is paired with a dynamic segment & middleware', async () => {
const browser = await next.browser('/')
await browser.elementByCss('[href="/foo/p/1"]').click()
await check(() => browser.elementById('modal').text(), /intercepted/)
await browser.refresh()
await check(() => browser.elementById('modal').text(), '')
await check(
() => browser.elementById('children').text(),
/not intercepted/
)
})
}
)
import { NextResponse, type NextRequest } from 'next/server'
export default async function middleware(request: NextRequest) {
const locale = 'en'
const { pathname } = request.nextUrl
const pathnameHasLocale =
pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
if (pathnameHasLocale) return
request.nextUrl.pathname = `/en${pathname}`
return NextResponse.rewrite(request.nextUrl)
}
export const config = {
matcher: ['/((?!api|_next|_vercel|.*\\..*).*)'],
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
...@@ -451,6 +451,9 @@ exports[`Next Build production mode first time setup with TypeScript 1`] = ` ...@@ -451,6 +451,9 @@ exports[`Next Build production mode first time setup with TypeScript 1`] = `
"no-var": [ "no-var": [
"error", "error",
], ],
"no-with": [
"off",
],
"prefer-const": [ "prefer-const": [
"error", "error",
], ],
......
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