Unverified Commit 000390a8 authored by Ben's avatar Ben Committed by GitHub

fix: detect proxy.ts correctly with compound pageExtensions (#93246)

## Maintainer status

- Current with `canary` as of 2026-05-18; this branch includes a clean
merge from latest `origin/canary`.
- Lightweight checks pass; full fork workflows are still
`action_required` until a maintainer approves CI.
- No unresolved review threads or failing jobs are reported after the
refresh.
- Review focus: shared convention-file basename extraction for proxy,
middleware, and instrumentation under compound `pageExtensions`; TS and
Rust paths use the same rule.

---

## Summary

Fixes #85648
Fixes #86303
Fixes #91600
Fixes #85646
Related to #86122
Fixes #92342
Closes #92934

When `pageExtensions` is set to compound extensions like `['page.ts',
'page.tsx']`, proxy files must be named `proxy.page.ts`. However, the
proxy detection logic used `file_stem()` (Rust/Turbopack) and
`path.parse().name` (JS/webpack), both of which only strip the **last**
extension — so `proxy.page.ts` becomes `proxy.page` instead of `proxy`,
and the proxy is never detected.

**Root cause:** `path.parse('proxy.page.ts').name` returns
`'proxy.page'`, not `'proxy'`. Same issue with Rust's `file_stem()`
which uses `rsplit_once('.')`.

**Fix:** Use `file_name().split('.')[0]` (JS) /
`file_name().split('.').next()` (Rust) to extract the first segment
before any dot. This correctly returns `'proxy'` for both `proxy.ts` and
`proxy.page.ts`.

The same `fileBaseName` extraction is also used for `middleware` and
`instrumentation` convention file detection, fixing compound
pageExtensions for those as well.

### Changes

- **Turbopack (Rust):** `crates/next-api/src/project.rs` (2 locations) +
`crates/next-api/src/middleware.rs` (1 location)
- **Webpack (JS):** `packages/next/src/build/index.ts` (build-time
detection) +
`packages/next/src/server/lib/router-utils/setup-dev-bundler.ts`
(dev-time detection)
- **E2e tests:**
- `proxy-page-extensions/` — proxy + instrumentation with compound
extensions
- `middleware-page-extensions/` — middleware with compound extensions
(separate fixture because the build refuses both `proxy.*` and
`middleware.*` simultaneously)

### Verified locally

| Mode | Bundler | Result |
|------|---------|--------|
| Dev | Turbopack | PASS (5/5) |
| Dev | Webpack | PASS (5/5) |
| Production (build+start) | Turbopack | PASS (5/5) |
| Production (build+start) | Webpack | PASS (5/5) |

Existing proxy test suites also verified (proxy-runtime-nodejs,
proxy-with-middleware, proxy-missing-export, proxy-runtime) — no
regressions.

## Test plan

- [x] `proxy-page-extensions.test.ts` covers proxy header injection,
page render through proxy, and `instrumentation.page.ts:register()`
running
- [x] `middleware-page-extensions.test.ts` covers middleware header
injection and page render through middleware
- [x] All 5 cases pass in dev/turbopack, dev/webpack, start/turbopack,
start/webpack
- [x] Existing proxy-runtime-nodejs tests pass (dev/webpack,
dev/turbopack, production/webpack)
- [ ] CI passes on all existing proxy tests

<!-- NEXT_JS_LLM_PR -->

---------
Co-authored-by: 's avatarNiklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
parent 12748456
...@@ -20,6 +20,7 @@ mod nft; ...@@ -20,6 +20,7 @@ mod nft;
mod nft_json; mod nft_json;
pub mod operation; pub mod operation;
mod pages; mod pages;
mod path_utils;
pub mod paths; pub mod paths;
pub mod project; pub mod project;
pub mod project_asset_hashes_manifest; pub mod project_asset_hashes_manifest;
......
...@@ -31,6 +31,7 @@ use turbopack_core::{ ...@@ -31,6 +31,7 @@ use turbopack_core::{
use crate::{ use crate::{
nft::{EndpointTraceResult, trace_endpoint}, nft::{EndpointTraceResult, trace_endpoint},
nft_json::NftJsonAsset, nft_json::NftJsonAsset,
path_utils::convention_file_base_name,
paths::{ paths::{
all_asset_paths, all_paths_in_root, get_asset_paths_from_root, get_js_paths_from_root, all_asset_paths, all_paths_in_root, get_asset_paths_from_root, get_js_paths_from_root,
get_wasm_paths_from_root, paths_to_bindings, wasm_paths_to_bindings, get_wasm_paths_from_root, paths_to_bindings, wasm_paths_to_bindings,
...@@ -84,7 +85,8 @@ impl MiddlewareEndpoint { ...@@ -84,7 +85,8 @@ impl MiddlewareEndpoint {
) )
.module(); .module();
let is_proxy = userland_module.ident().await?.path.file_stem() == Some("proxy"); let is_proxy =
convention_file_base_name(userland_module.ident().await?.path.file_name()) == "proxy";
let module = get_middleware_module( let module = get_middleware_module(
*self.asset_context, *self.asset_context,
......
/// Extract the convention base name (e.g. `"proxy"`, `"middleware"`) from a
/// filename.
///
/// Returns the segment before the first dot — NOT what `file_stem()` returns.
/// `file_stem()` only strips the last extension, which is wrong here: with a
/// compound `pageExtensions` entry like `"page.ts"`, the file `proxy.page.ts`
/// has `file_stem() == Some("proxy.page")`, but its convention base name is
/// `"proxy"`.
///
/// This must stay in lockstep with the TypeScript
/// `getConventionFileBaseName` helper used by the webpack build path (see
/// `packages/next/src/build/get-convention-file-base-name.ts`). Any change
/// here needs the same change there.
pub fn convention_file_base_name(file_name: &str) -> &str {
file_name.split('.').next().unwrap_or(file_name)
}
...@@ -106,6 +106,7 @@ use crate::{ ...@@ -106,6 +106,7 @@ use crate::{
middleware::MiddlewareEndpoint, middleware::MiddlewareEndpoint,
next_server_nft::{pages_renderer_modules, require_hook_modules}, next_server_nft::{pages_renderer_modules, require_hook_modules},
pages::PagesProject, pages::PagesProject,
path_utils::convention_file_base_name,
route::{ route::{
Endpoint, EndpointGroup, EndpointGroupEntry, EndpointGroupKey, EndpointGroups, Endpoints, Endpoint, EndpointGroup, EndpointGroupEntry, EndpointGroupKey, EndpointGroups, Endpoints,
Route, Route,
...@@ -2041,7 +2042,7 @@ impl Project { ...@@ -2041,7 +2042,7 @@ impl Project {
let middleware = self.find_middleware(); let middleware = self.find_middleware();
let middleware = if let FindContextFileResult::Found(fs_path, _) = &*middleware.await? { let middleware = if let FindContextFileResult::Found(fs_path, _) = &*middleware.await? {
let is_proxy = fs_path.file_stem() == Some("proxy"); let is_proxy = convention_file_base_name(fs_path.file_name()) == "proxy";
Some(Middleware { Some(Middleware {
endpoint: self.middleware_endpoint().to_resolved().await?, endpoint: self.middleware_endpoint().to_resolved().await?,
is_proxy, is_proxy,
...@@ -2220,7 +2221,7 @@ impl Project { ...@@ -2220,7 +2221,7 @@ impl Project {
.as_ref() .as_ref()
.map(|_| AppProject::client_transition_name()); .map(|_| AppProject::client_transition_name());
let is_proxy = fs_path.file_stem() == Some("proxy"); let is_proxy = convention_file_base_name(fs_path.file_name()) == "proxy";
let config = parse_segment_config_from_source( let config = parse_segment_config_from_source(
source, source,
if is_proxy { if is_proxy {
......
/**
* Extract the convention base name (e.g. `"proxy"`, `"middleware"`,
* `"instrumentation"`) from a filename.
*
* Returns the segment before the first dot — NOT what `path.parse().name`
* returns. The stdlib only strips the last extension, which is wrong here:
* with a compound `pageExtensions` entry like `"page.ts"` the file
* `proxy.page.ts` has `path.parse().name === "proxy.page"`, but its
* convention base name is `"proxy"`.
*
* This must stay in lockstep with the Rust `convention_file_base_name`
* helper used by the Turbopack build path (see
* `crates/next-api/src/path_utils.rs`). Any change here needs the same
* change there.
*/
export function getConventionFileBaseName(fileBase: string): string {
return fileBase.split('.', 1)[0]
}
...@@ -118,6 +118,7 @@ import type { EventBuildFeatureUsage } from '../telemetry/events' ...@@ -118,6 +118,7 @@ import type { EventBuildFeatureUsage } from '../telemetry/events'
import { Telemetry } from '../telemetry/storage' import { Telemetry } from '../telemetry/storage'
import { discoverRoutes, createPagesMapping } from './route-discovery' import { discoverRoutes, createPagesMapping } from './route-discovery'
import { sortByPageExts } from './sort-by-page-exts' import { sortByPageExts } from './sort-by-page-exts'
import { getConventionFileBaseName } from './get-convention-file-base-name'
import { getStaticInfoIncludingLayouts } from './get-static-info-including-layouts' import { getStaticInfoIncludingLayouts } from './get-static-info-including-layouts'
import { PAGE_TYPES } from '../lib/page-types' import { PAGE_TYPES } from '../lib/page-types'
import { generateBuildId } from './generate-build-id' import { generateBuildId } from './generate-build-id'
...@@ -1404,7 +1405,8 @@ export default async function build( ...@@ -1404,7 +1405,8 @@ export default async function build(
let middlewareFilePath: string | undefined let middlewareFilePath: string | undefined
for (const rootPath of rootPaths) { for (const rootPath of rootPaths) {
const { name: fileBaseName, dir: fileDir } = path.parse(rootPath) const { base: fileBase, dir: fileDir } = path.parse(rootPath)
const fileBaseName = getConventionFileBaseName(fileBase)
const normalizedFileDir = normalizePathSep(fileDir) const normalizedFileDir = normalizePathSep(fileDir)
const isAtConventionLevel = const isAtConventionLevel =
......
...@@ -30,6 +30,7 @@ import { ...@@ -30,6 +30,7 @@ import {
} from '../../../telemetry/events' } from '../../../telemetry/events'
import { getSortedRoutes } from '../../../shared/lib/router/utils' import { getSortedRoutes } from '../../../shared/lib/router/utils'
import { sortByPageExts } from '../../../build/sort-by-page-exts' import { sortByPageExts } from '../../../build/sort-by-page-exts'
import { getConventionFileBaseName } from '../../../build/get-convention-file-base-name'
import { normalizeCatchAllRoutes } from './normalize-catchall-routes' import { normalizeCatchAllRoutes } from './normalize-catchall-routes'
import { verifyAndRunTypeScript } from '../../../lib/verify-typescript-setup' import { verifyAndRunTypeScript } from '../../../lib/verify-typescript-setup'
import { verifyPartytownSetup } from '../../../lib/verify-partytown-setup' import { verifyPartytownSetup } from '../../../lib/verify-partytown-setup'
...@@ -544,7 +545,8 @@ async function startWatcher( ...@@ -544,7 +545,8 @@ async function startWatcher(
continue continue
} }
const { name: fileBaseName, dir: fileDir } = path.parse(fileName) const { base: fileBase, dir: fileDir } = path.parse(fileName)
const fileBaseName = getConventionFileBaseName(fileBase)
const isAtConventionLevel = const isAtConventionLevel =
fileDir === dir || fileDir === path.join(dir, 'src') fileDir === dir || fileDir === path.join(dir, 'src')
......
export default function Loading() {
return <p>Loading headers...</p>
}
import { headers } from 'next/headers'
export default async function HeadersPage() {
const hdrs = await headers()
return (
<dl>
<dt>x-from-middleware</dt>
<dd id="middleware-header">
{hdrs.get('x-from-middleware') ?? 'MISSING'}
</dd>
</dl>
)
}
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
<title>middleware-page-extensions</title>
</head>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello from middleware-page-extensions</p>
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('middleware-page-extensions', () => {
const { next } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
it('should execute middleware.page.ts and set custom header', async () => {
const res = await next.fetch('/headers')
expect(res.status).toBe(200)
const html = await res.text()
expect(html).toContain('hello-from-middleware')
})
it('should render the page through the middleware', async () => {
const res = await next.fetch('/')
expect(res.status).toBe(200)
const html = await res.text()
expect(html).toContain('hello from middleware-page-extensions')
})
it('should warn that the middleware convention is deprecated in favor of proxy', async () => {
// The deprecation warnOnce is fired the first time the middleware
// convention is detected. nextTestSetup waits for "ready" but the log
// may still be flushing, so poll.
await retry(async () => {
expect(next.cliOutput).toContain(
'The "middleware" file convention is deprecated. Please use "proxy" instead.'
)
})
})
})
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
return NextResponse.next({
request: {
headers: new Headers({
...Object.fromEntries(request.headers),
'x-from-middleware': 'hello-from-middleware',
}),
},
})
}
module.exports = {
pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js'],
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>this fixture should never render</p>
}
import { NextResponse } from 'next/server'
export function middleware() {
return NextResponse.next()
}
/** @type {import('next').NextConfig} */
module.exports = {
pageExtensions: ['page.tsx', 'page.ts'],
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('proxy-and-middleware-conflict', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
})
if (skipped) {
return
}
if (isNextDev) {
beforeAll(async () => {
// The dev bundler discovers both files during its first compile,
// logs the conflict to stderr, and surfaces it as an unhandled
// rejection but keeps the server process alive. Starting succeeds;
// we just need the boot-time scan to have run.
await next.start()
})
} else {
beforeAll(async () => {
try {
await next.build()
} catch {
// Expect build error.
}
})
}
it('should report that both middleware and proxy files are present', async () => {
await retry(() => {
expect(next.cliOutput).toContain(
'are detected. Please use "./proxy.page.ts" only.'
)
})
})
})
import { NextResponse } from 'next/server'
export function proxy() {
return NextResponse.next()
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello from proxy-mixed-page-extensions</p>
}
/** @type {import('next').NextConfig} */
module.exports = {
// Mix a compound entry (`page.tsx`) and a simple entry (`tsx`) so that
// `proxy.page.tsx` is recognized as a proxy via the compound rule while
// simple-extension routes (`app/page.tsx`) keep working alongside it.
pageExtensions: ['page.tsx', 'tsx'],
}
import { nextTestSetup } from 'e2e-utils'
describe('proxy-mixed-page-extensions', () => {
const { next } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
it('should detect proxy.page.tsx when pageExtensions mixes compound and simple', async () => {
// pageExtensions = ['page.tsx', 'tsx']: the compound rule must still
// recognize `proxy.page.tsx` as a proxy. The simple rule (`tsx`)
// shouldn't accidentally take over and route the file as something
// else, nor should the convention loop confuse `proxy.page.tsx` with
// a non-proxy file.
const res = await next.fetch('/')
expect(res.status).toBe(200)
expect(res.headers.get('x-proxy-ran')).toBe('true')
const html = await res.text()
expect(html).toContain('hello from proxy-mixed-page-extensions')
})
})
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function proxy(_request: NextRequest) {
const response = NextResponse.next()
response.headers.set('x-proxy-ran', 'true')
return response
}
export default function Loading() {
return <p>Loading headers...</p>
}
import { headers } from 'next/headers'
export default async function HeadersPage() {
const hdrs = await headers()
return (
<dl>
<dt>x-from-proxy</dt>
<dd id="proxy-header">{hdrs.get('x-from-proxy') ?? 'MISSING'}</dd>
</dl>
)
}
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
<title>proxy-page-extensions</title>
</head>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello from proxy-page-extensions</p>
}
export async function register() {
console.log('instrumentation.page.ts:register')
}
module.exports = {
pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js'],
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('proxy-page-extensions', () => {
const { next } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
it('should execute proxy.page.ts and set custom header', async () => {
const res = await next.fetch('/headers')
expect(res.status).toBe(200)
const html = await res.text()
expect(html).toContain('hello-from-proxy')
})
it('should render the page through the proxy', async () => {
const res = await next.fetch('/')
expect(res.status).toBe(200)
// Asserting the response header proves the proxy actually ran on this
// route — the page body alone would render even with a broken proxy.
expect(res.headers.get('x-proxy-ran')).toBe('true')
const html = await res.text()
expect(html).toContain('hello from proxy-page-extensions')
})
it('should detect instrumentation.page.ts and run register()', async () => {
// `register()` is invoked once during server boot, before any request is
// served, so we don't need to make a request first. retry() handles the
// case where the cliOutput buffer was flushed slightly after server boot.
await retry(async () => {
expect(next.cliOutput).toContain('instrumentation.page.ts:register')
})
})
})
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function proxy(request: NextRequest) {
const response = NextResponse.next({
request: {
headers: new Headers({
...Object.fromEntries(request.headers),
'x-from-proxy': 'hello-from-proxy',
}),
},
})
// Expose a response header so route-level tests can verify the proxy
// actually ran without forcing the page to opt into dynamic rendering.
response.headers.set('x-proxy-ran', 'true')
return response
}
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