Unverified Commit 668cd3a4 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

fix: preserve middleware rewrite query in Pages API routes (#94905)

### What?

- Preserve the resolved routing `query` and dynamic `params` when
`NextNodeServer.runApi` invokes a bundled Pages API route.
- Keep `req.url` restored to the original browser-visible request URL
for compatibility.
- Add an end-to-end regression test for a middleware rewrite from
`/foo/bar?key=value` to `/api/proxy/bar?added=1&extra=2` using an
optional catch-all Pages API route.

### Why?

Middleware routing correctly resolves the destination query and
catch-all parameters, but the Node Pages API path restores `req.url`
before invoking the bundled handler and previously forwarded only
`waitUntil`. The handler then reparsed the original URL and produced
only `{ key: "value" }`, dropping the rewrite-added `added` and `extra`
values and the destination `slug` parameter.

This restores the behavior from Next.js 14 that regressed during the
Pages API handler-interface migration. The issue affects both webpack
and Turbopack because the data is lost in shared server routing after
bundling.

The public documentation describes the pieces separately—rewrites
preserve the original URL, dynamic API parameters appear in `req.query`,
and resolved routing queries include middleware changes—so this is a bug
fix rather than a new API contract.

Fixes #94647

### How?

`runApi` now forwards the existing request metadata together with the
resolved `query` and `match.params` through the bundled handler context.
The Pages API entrypoint already installs supplied request metadata
before `routeModule.prepare()`, which then uses these routed values
while retaining the original `req.url`.

The regression test asserts that:

- `req.url` remains `/foo/bar?key=value`.
- `req.query` contains the original `key`, rewrite-added `added` and
`extra`, and catch-all `slug` values.

### Verification

- `pnpm --filter=next build`
- `NEXT_TEST_PREFER_OFFLINE=1 pnpm test-dev-turbo
test/e2e/middleware-rewrites/test/index.test.ts -t "should preserve
rewrite query and dynamic params in Pages API routes"`
- `NEXT_TEST_PREFER_OFFLINE=1 pnpm test-dev-webpack
test/e2e/middleware-rewrites/test/index.test.ts -t "should preserve
rewrite query and dynamic params in Pages API routes"`
- `NEXT_TEST_PREFER_OFFLINE=1 pnpm test-start-turbo
test/e2e/middleware-rewrites/test/index.test.ts -t "should preserve
rewrite query and dynamic params in Pages API routes"`
- `NEXT_TEST_PREFER_OFFLINE=1 pnpm test-start-webpack
test/e2e/middleware-rewrites/test/index.test.ts -t "should preserve
rewrite query and dynamic params in Pages API routes"`
- `NEXT_TEST_PREFER_OFFLINE=1 pnpm test-dev-turbo
test/e2e/api-support/api-support.test.ts -t "query|dynamic"`
- `NEXT_TEST_PREFER_OFFLINE=1 pnpm test-start-webpack
test/e2e/api-support/api-support.test.ts -t "query|dynamic"`
- `NEXT_TEST_PREFER_OFFLINE=1 pnpm test-dev-turbo
test/e2e/custom-routes/custom-routes.test.ts -t "api rewrite"`
- `NEXT_TEST_PREFER_OFFLINE=1 pnpm test-start-webpack
test/e2e/custom-routes/custom-routes.test.ts -t "api rewrite"`
- Pre-commit lint-staged checks (Prettier and ESLint)
- Not run continuously: `pnpm --filter=next dev` (the local watcher hits
the environment open-file limit with `EMFILE`; the focused package build
passed)

<!-- NEXT_JS_LLM_PR -->

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes shared Pages API request routing in the Node server and
adapter i18n route generation; behavior is restored to pre-regression
semantics but affects all bundled Pages API invocations.
> 
> **Overview**
> Fixes a regression where **Pages API** handlers saw only the original
URL query after a middleware rewrite, because `runApi` restored
`req.url` but did not pass the router’s resolved `query` and `params`
into the bundled handler context.
> 
> `NextNodeServer.runApi` now supplies `requestMeta` (including merged
`query` and `match.params`) alongside `waitUntil`, so `req.query` keeps
rewrite-added parameters and catch-all segments while `req.url` stays
the browser-visible path.
> 
> Adapter build output no longer applies i18n locale prefixing to
dynamic **Pages API** routes (`shouldLocalize` excludes API pages);
regular pages still get `nextLocale` routing.
> 
> Regression coverage: middleware rewrite e2e (`/foo/bar` → catch-all
API) and a production adapter test with `i18n` enabled.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ad415cfe574f67dd7385662a01c2c9f3c89af521. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
parent b1f49163
...@@ -54,6 +54,7 @@ import { defaultOverrides } from '../../server/require-hook' ...@@ -54,6 +54,7 @@ import { defaultOverrides } from '../../server/require-hook'
import { generateRoutesManifest } from '../generate-routes-manifest' import { generateRoutesManifest } from '../generate-routes-manifest'
import { Bundler } from '../../lib/bundler' import { Bundler } from '../../lib/bundler'
import { resolveCacheHandlerPathToFilesystem } from '../../lib/format-dynamic-import-path' import { resolveCacheHandlerPathToFilesystem } from '../../lib/format-dynamic-import-path'
import { isAPIRoute } from '../../lib/is-api-route'
interface SharedRouteFields { interface SharedRouteFields {
/** /**
...@@ -1871,7 +1872,7 @@ export async function handleBuildComplete({ ...@@ -1871,7 +1872,7 @@ export async function handleBuildComplete({
] ]
for (const route of routesManifest.dynamicRoutes) { for (const route of routesManifest.dynamicRoutes) {
const shouldLocalize = config.i18n const shouldLocalize = Boolean(config.i18n) && !isAPIRoute(route.page)
const routeRegex = getNamedRouteRegex(route.page, { const routeRegex = getNamedRouteRegex(route.page, {
prefixRouteKeys: true, prefixRouteKeys: true,
......
...@@ -583,6 +583,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -583,6 +583,7 @@ export default class NextNodeServer extends BaseServer<
res: ServerResponse, res: ServerResponse,
ctx: { ctx: {
waitUntil: ReturnType<BaseServer['getWaitUntil']> waitUntil: ReturnType<BaseServer['getWaitUntil']>
requestMeta?: RequestMeta
} }
) => Promise<void> ) => Promise<void>
} }
...@@ -594,6 +595,11 @@ export default class NextNodeServer extends BaseServer< ...@@ -594,6 +595,11 @@ export default class NextNodeServer extends BaseServer<
addRequestMeta(req.originalRequest, 'distDir', this.distDir) addRequestMeta(req.originalRequest, 'distDir', this.distDir)
await module.handler(req.originalRequest, res.originalResponse, { await module.handler(req.originalRequest, res.originalResponse, {
waitUntil: this.getWaitUntil(), waitUntil: this.getWaitUntil(),
requestMeta: {
...getRequestMeta(req.originalRequest),
query,
params: match.params,
},
}) })
return true return true
} }
......
...@@ -67,6 +67,14 @@ export async function middleware(request) { ...@@ -67,6 +67,14 @@ export async function middleware(request) {
) )
} }
if (url.pathname === '/foo/bar') {
const rewriteUrl = request.nextUrl.clone()
rewriteUrl.pathname = '/api/proxy/bar/'
rewriteUrl.searchParams.set('added', '1')
rewriteUrl.searchParams.set('extra', '2')
return NextResponse.rewrite(rewriteUrl)
}
if (url.pathname.includes('/rewrite-to-static')) { if (url.pathname.includes('/rewrite-to-static')) {
request.nextUrl.pathname = '/static-ssg/post-1' request.nextUrl.pathname = '/static-ssg/post-1'
return NextResponse.rewrite(request.nextUrl) return NextResponse.rewrite(request.nextUrl)
......
export default function handler(req, res) {
res.status(200).json({
url: req.url,
query: req.query,
})
}
...@@ -7,7 +7,7 @@ import { FileRef, nextTestSetup } from 'e2e-utils' ...@@ -7,7 +7,7 @@ import { FileRef, nextTestSetup } from 'e2e-utils'
import escapeStringRegexp from 'escape-string-regexp' import escapeStringRegexp from 'escape-string-regexp'
describe('Middleware Rewrite', () => { describe('Middleware Rewrite', () => {
const { next } = nextTestSetup({ const { next, isNextDeploy } = nextTestSetup({
files: { files: {
pages: new FileRef(join(__dirname, '../app/pages')), pages: new FileRef(join(__dirname, '../app/pages')),
'next.config.js': new FileRef(join(__dirname, '../app/next.config.js')), 'next.config.js': new FileRef(join(__dirname, '../app/next.config.js')),
...@@ -93,6 +93,26 @@ describe('Middleware Rewrite', () => { ...@@ -93,6 +93,26 @@ describe('Middleware Rewrite', () => {
expect(json.headers['x-hello-from-middleware1']).toBe('hello') expect(json.headers['x-hello-from-middleware1']).toBe('hello')
}) })
// Regression test for https://github.com/vercel/next.js/issues/94647.
it('should preserve rewrite query and dynamic params in Pages API routes', async () => {
const res = await next.fetch('/foo/bar?key=value')
expect(res.status).toBe(200)
expect(await res.json()).toEqual({
// Deployed proxies include query values added while resolving rewrites
// in the URL passed to the function. Locally they are only in req.query.
url: isNextDeploy
? '/foo/bar?key=value&added=1&extra=2'
: '/foo/bar?key=value',
query: {
key: 'value',
added: '1',
extra: '2',
slug: ['bar'],
},
})
})
it('should handle static dynamic rewrite from middleware correctly', async () => { it('should handle static dynamic rewrite from middleware correctly', async () => {
const browser = await next.browser('/rewrite-to-static') const browser = await next.browser('/rewrite-to-static')
......
import { nextTestSetup } from 'e2e-utils'
import type { NextAdapter } from 'next'
describe('adapter config with i18n API routes', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('does not localize dynamic Pages API routes', async () => {
const { outputs, routing }: Parameters<NextAdapter['onBuildComplete']>[0] =
await next.readJSON('build-complete.json')
const apiOutput = outputs.pagesApi.find(
(output) => output.pathname === '/api/proxy/[[...slug]]'
)
const apiRoute = routing.dynamicRoutes.find(
(route) => route.source === '/api/proxy/[[...slug]]'
)
const pageRoute = routing.dynamicRoutes.find(
(route) => route.source === '/blog/[slug]'
)
expect(apiOutput).toBeDefined()
expect(apiRoute).toBeDefined()
expect(apiRoute?.sourceRegex).not.toContain('nextLocale')
expect(apiRoute?.destination).toBe(
'/api/proxy/[[...slug]]?nxtPslug=$nxtPslug'
)
expect(pageRoute).toBeDefined()
expect(pageRoute?.sourceRegex).toContain('nextLocale')
expect(pageRoute?.destination).toBe(
'/$nextLocale/blog/[slug]?nxtPslug=$nxtPslug'
)
})
})
import fs from 'fs/promises'
// @ts-check
/** @type {import('next').NextAdapter} */
const adapter = {
name: 'i18n-api-test-adapter',
async onBuildComplete(ctx) {
await fs.writeFile('build-complete.json', JSON.stringify(ctx, null, 2))
},
}
export default adapter
import Module from 'module'
const require = Module.createRequire(import.meta.url)
/** @type {import('next').NextConfig} */
const nextConfig = {
adapterPath: require.resolve('./my-adapter.mjs'),
i18n: {
locales: ['en', 'fr'],
defaultLocale: 'en',
},
}
export default nextConfig
import type { NextApiRequest, NextApiResponse } from 'next'
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json(req.query)
}
export default function Page() {
return <p>blog</p>
}
export default function Page() {
return <p>hello world</p>
}
...@@ -502,5 +502,18 @@ function getPrerenderOutput(cliOutput: string): string { ...@@ -502,5 +502,18 @@ function getPrerenderOutput(cliOutput: string): string {
} }
} }
return lines.join('\n').trim() const output = lines.join('\n').trim()
const summaryIndex = output.indexOf('\n\n> Export encountered errors')
if (summaryIndex === -1) {
return output
}
// Routes prerender concurrently, so their errors can be reported in any order.
const errors = output
.slice(0, summaryIndex)
.split(/(?=^Error: Route )/m)
.sort()
return `${errors.join('')}${output.slice(summaryIndex)}`
} }
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