Unverified Commit 8eaf44b0 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

Fixed rewrite param parsing for interception routes in Vercel deployments (#79204)

> [!NOTE]
> - Introduced in [PR #67400](https://github.com/vercel/next.js/pull/67400) and released in [v15.0.0-canary.54](https://github.com/vercel/next.js/releases/tag/v15.0.0-canary.54)
> - See failed test in deployment [GitHub Actions Run](https://github.com/vercel/next.js/actions/runs/15083957601/job/42405327124?pr=79204#step:34:92)

### Summary

This PR resolves two issues related to interception routes and rewrite behavior in Vercel deployments:

1. Rewrite params not parsed correctly from the `NEXT_ROUTER_STATE_TREE_HEADER`, resulting in server crashes due to missing dynamic params.
2. Malformed search query from Vercel deployment, where unresolved dynamic params like `:foo_id` were passed instead of actual values like `1`.

These issues caused runtime errors and incorrect component behavior during navigation in deployed environments. This PR ensures consistent param resolution across local and deployed environments.

### Issue 1: Missing Rewrite Params in Vercel

The `NEXT_ROUTER_STATE_TREE_HEADER` header, introduced in PR [#67400](https://github.com/vercel/next.js/pull/67400), wasn't parsed correctly during Vercel deployment. This was fine locally with `next start`, which uses [`getResolveRoutes`](https://github.com/vercel/next.js/blob/42b1c400c977cbe43147c083714e7f6bd38cff80/packages/next/src/shared/lib/router/utils/resolve-rewrites.ts#L14), but broke in Vercel which used [`handleRewrites`](https://github.com/vercel/next.js/blob/42b1c400c977cbe43147c083714e7f6bd38cff80/packages/next/src/server/server-utils.ts#L208).

```
TypeError: Expected "<a_dynamic_route_slug>" to be a string
    at async Object.handler (___next_launcher.cjs:58:5)
    at async Server.r (../../opt/rust/nodejs.js:2:14674)
    at async Server.<anonymous> (../../opt/rust/nodejs.js:16:6262)
```

This occurred because the expected dynamic route params were undefined, causing `path-to-regexp` to throw when trying to compile the destination path.

### Solution

We ported the interception route rewrite logic from PR #67400, allowing consistent resolution of route params from the `NEXT_ROUTER_STATE_TREE_HEADER`.

### Issue 2: Malformed Query from Vercel

Even after correct interception routing, the query string received from Vercel contained unresolved params such as `:foo_id`, resulting in:

```ts
{
  rsc: 'aaaaa',
  nxtPfoo_id: ':foo_id',
  nxtPbar_id: ':bar_id',
  nxtPbaz: '1',
}
```

Instead of the expected:

```ts
{
  rsc: 'aaaaa',
  nxtPfoo_id: '1',
  nxtPbar_id: '1',
  nxtPbaz: '1',
}
```

This happened because the rewrite rule:

```json
{
  "source": "/:baz_id",
  "destination": "/:foo_id/:bar_id/(...)baz/:baz_id",
  ...
}
```

Did not include `:foo_id` or `:bar_id` in the `source`, so they were never correctly mapped by Vercel CLI's [`convertRewrites`](https://github.com/vercel/vercel/blob/53e3609f144d08ad92d42291bcbf483ae592ff1b/packages/routing-utils/src/superstatic.ts#L165).

### Solution

Since we already parse rewrite params from the `NEXT_ROUTER_STATE_TREE_HEADER`, we now inject those resolved values into `parsedUrl.query`. If any query value still starts with `:`, it's treated as unexpected and replaced with the rewrite params accordingly.
parent 5333dda8
---
'next': patch
---
Fixed rewrite params of the interception routes not being parsed correctly in certain deployed environments
...@@ -27,6 +27,10 @@ import { decodeQueryPathParameter } from './lib/decode-query-path-parameter' ...@@ -27,6 +27,10 @@ import { decodeQueryPathParameter } from './lib/decode-query-path-parameter'
import type { DeepReadonly } from '../shared/lib/deep-readonly' import type { DeepReadonly } from '../shared/lib/deep-readonly'
import { parseReqUrl } from '../lib/url' import { parseReqUrl } from '../lib/url'
import { formatUrl } from '../shared/lib/router/utils/format-url' import { formatUrl } from '../shared/lib/router/utils/format-url'
import { parseAndValidateFlightRouterState } from './app-render/parse-and-validate-flight-router-state'
import { isInterceptionRouteRewrite } from '../lib/generate-interception-routes-rewrites'
import { NEXT_ROUTER_STATE_TREE_HEADER } from '../client/components/app-router-headers'
import { getSelectedParams } from '../client/components/router-reducer/compute-changed-path'
export function normalizeCdnUrl( export function normalizeCdnUrl(
req: BaseNextRequest | IncomingMessage, req: BaseNextRequest | IncomingMessage,
...@@ -209,7 +213,7 @@ export function getServerUtils({ ...@@ -209,7 +213,7 @@ export function getServerUtils({
req: BaseNextRequest | IncomingMessage, req: BaseNextRequest | IncomingMessage,
parsedUrl: UrlWithParsedQuery parsedUrl: UrlWithParsedQuery
) { ) {
const rewriteParams = {} const rewriteParams: Record<string, string> = {}
let fsPathname = parsedUrl.pathname let fsPathname = parsedUrl.pathname
const matchesPage = () => { const matchesPage = () => {
...@@ -250,6 +254,28 @@ export function getServerUtils({ ...@@ -250,6 +254,28 @@ export function getServerUtils({
} }
if (params) { if (params) {
try {
// An interception rewrite might reference a dynamic param for a route the user
// is currently on, which wouldn't be extractable from the matched route params.
// This attempts to extract the dynamic params from the provided router state.
if (isInterceptionRouteRewrite(rewrite as Rewrite)) {
const stateHeader =
req.headers[NEXT_ROUTER_STATE_TREE_HEADER.toLowerCase()]
if (stateHeader) {
params = {
...getSelectedParams(
parseAndValidateFlightRouterState(stateHeader)
),
...params,
}
}
}
} catch (err) {
// this is a no-op -- we couldn't extract dynamic params from the provided router state,
// so we'll just use the params from the route matcher
}
const { parsedDestination, destQuery } = prepareDestination({ const { parsedDestination, destQuery } = prepareDestination({
appendParamsToQuery: true, appendParamsToQuery: true,
destination: rewrite.destination, destination: rewrite.destination,
...@@ -266,6 +292,20 @@ export function getServerUtils({ ...@@ -266,6 +292,20 @@ export function getServerUtils({
Object.assign(parsedUrl.query, parsedDestination.query) Object.assign(parsedUrl.query, parsedDestination.query)
delete (parsedDestination as any).query delete (parsedDestination as any).query
// for each property in parsedUrl.query, if the value is parametrized (eg :foo), look up the value
// in rewriteParams and replace the parametrized value with the actual value
// this is used when the rewrite destination does not contain the original source param
// and so the value is still parametrized and needs to be replaced with the actual rewrite param
Object.entries(parsedUrl.query).forEach(([key, value]) => {
if (value && typeof value === 'string' && value.startsWith(':')) {
const paramName = value.slice(1)
const actualValue = rewriteParams[paramName]
if (actualValue) {
parsedUrl.query[key] = actualValue
}
}
})
Object.assign(parsedUrl, parsedDestination) Object.assign(parsedUrl, parsedDestination)
fsPathname = parsedUrl.pathname fsPathname = parsedUrl.pathname
......
export default function Layout(props: {
children: React.ReactNode
modal: React.ReactNode
}) {
return (
<>
{props.children}
{props.modal}
</>
)
}
import Link from 'next/link'
export default async function Page(props: {
params: Promise<{ foo_id: string; bar_id: string }>
}) {
const params = await props.params
return (
<>
<h1>
foo id {params.foo_id}, bar id {params.bar_id}
</h1>
<Link href="/baz_id/1">Link to bug report 1</Link>
</>
)
}
export default async function Home({
params,
}: {
params: Promise<{ baz_id: string }>
}) {
const { baz_id } = await params
return <p>baz_id/{baz_id}</p>
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
export default function Home() {
return <Link href="/1/1">Start from /1/1</Link>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
describe('parallel-routes-and-interception-nested-dynamic-routes', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should intercept the route for nested dynamic routes', async () => {
const browser = await next.browser('/1/1')
expect(await browser.elementByCss('h1').text()).toBe('foo id 1, bar id 1')
await browser.elementByCss('a').click()
// Should intercept the route.
expect(await browser.waitForElementByCss('p').text()).toBe('intercepted!')
// Should preserve the previous component.
expect(await browser.elementByCss('h1').text()).toBe('foo id 1, bar id 1')
await browser.refresh()
// Should display the correct /baz_id/1 content.
expect(await browser.waitForElementByCss('p').text()).toBe('baz_id/1')
})
})
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