Commit b0a97c16 authored by Ben Gubler's avatar Ben Gubler Committed by Janka Uryga

feat: block next/root-params imports in middleware and instrumentation layers

Add a webpack rule that errors when next/root-params is imported from
middleware or instrumentation layers. Previously these imports would
compile successfully with only a warning and the value would be
undefined at runtime.

Also switch the root-params rules from absolute path matching (resource)
to regex matching (test) for reliability in isolated CI environments.

On the Turbopack side, make the ServerContextType match exhaustive in the
root-params mapper. Add Pages to the blocked list, improving an error
where it fell through the wildcard and produced a misleading "Client
Component" message instead of "App Directory".
parent 82829bc5
...@@ -116,18 +116,18 @@ impl NextRootParamsMapper { ...@@ -116,18 +116,18 @@ impl NextRootParamsMapper {
})?; })?;
Self::valid_import_map_result(collected_root_params) Self::valid_import_map_result(collected_root_params)
} }
ServerContextType::PagesApi { .. } ServerContextType::Pages { .. }
| ServerContextType::PagesApi { .. }
| ServerContextType::Instrumentation { .. } | ServerContextType::Instrumentation { .. }
| ServerContextType::Middleware { .. } => { | ServerContextType::Middleware { .. } => {
// There's no sensible way to use root params outside of the app // There's no sensible way to use root params outside of the app
// directory. TODO: make sure this error is // directory.
// consistent with webpack
Self::invalid_import_map_result( Self::invalid_import_map_result(
"'next/root-params' can only be used inside the App Directory." "'next/root-params' can only be used inside the App Directory."
.into(), .into(),
) )
} }
_ => { ServerContextType::AppSSR { .. } => {
// In general, the compiler should prevent importing 'next/root-params' // In general, the compiler should prevent importing 'next/root-params'
// from client modules, but it doesn't catch // from client modules, but it doesn't catch
// everything. If an import slips through // everything. If an import slips through
......
...@@ -2869,12 +2869,14 @@ function getNextRootParamsRules({ ...@@ -2869,12 +2869,14 @@ function getNextRootParamsRules({
appDir: string | undefined appDir: string | undefined
pageExtensions: string[] pageExtensions: string[]
}): webpack.RuleSetRule[] { }): webpack.RuleSetRule[] {
// Match resolved import of 'next/root-params' // Match resolved import of 'next/root-params'.
const nextRootParamsModule = path.join(NEXT_PROJECT_ROOT, 'root-params.js') // Use a regex (not an absolute path) so it works in isolated CI environments
// where the resolved path differs from the local build.
const nextRootParamsModuleTest = /[\\/]next[\\/]root-params\.js$/
const createInvalidImportRule = (message: string) => { const createInvalidImportRule = (message: string) => {
return { return {
resource: nextRootParamsModule, test: nextRootParamsModuleTest,
loader: 'next-invalid-import-error-loader', loader: 'next-invalid-import-error-loader',
options: { options: {
message, message,
...@@ -2906,6 +2908,16 @@ function getNextRootParamsRules({ ...@@ -2906,6 +2908,16 @@ function getNextRootParamsRules({
const invalidClientImportRule = createInvalidImportRule( const invalidClientImportRule = createInvalidImportRule(
"'next/root-params' cannot be imported from a Client Component module. It should only be used from a Server Component." "'next/root-params' cannot be imported from a Client Component module. It should only be used from a Server Component."
) )
const invalidNonAppServerImportRule = {
test: nextRootParamsModuleTest,
loader: 'next-invalid-import-error-loader',
issuerLayer: {
or: [WEBPACK_LAYERS.instrument, WEBPACK_LAYERS.middleware],
},
options: {
message: "'next/root-params' can only be used inside the App Directory.",
} satisfies InvalidImportLoaderOpts,
} satisfies webpack.RuleSetRule
// in the browser compilation we can skip the server rules, because we know all imports will be invalid. // in the browser compilation we can skip the server rules, because we know all imports will be invalid.
if (isClient) { if (isClient) {
...@@ -2915,8 +2927,9 @@ function getNextRootParamsRules({ ...@@ -2915,8 +2927,9 @@ function getNextRootParamsRules({
return [ return [
{ {
oneOf: [ oneOf: [
invalidNonAppServerImportRule,
{ {
resource: nextRootParamsModule, test: nextRootParamsModuleTest,
issuerLayer: shouldUseReactServerCondition as ( issuerLayer: shouldUseReactServerCondition as (
layer: string layer: string
) => boolean, ) => boolean,
......
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <h1>hello world</h1>
}
module.exports = {
experimental: { rootParams: true },
}
import { lang } from 'next/root-params'
export function register() {
console.log(lang)
}
import { lang } from 'next/root-params'
export default function middleware() {
console.log(lang)
}
import { nextTestSetup, FileRef } from 'e2e-utils'
import { join } from 'path'
const fixturesDir = join(__dirname, 'fixtures')
const baseDir = join(fixturesDir, 'base')
function baseFilesWith(extraFiles: Record<string, FileRef>) {
return {
app: new FileRef(join(baseDir, 'app')),
'next.config.js': new FileRef(join(baseDir, 'next.config.js')),
...extraFiles,
}
}
describe('next/root-params blocked layers', () => {
const expectedError =
"'next/root-params' can only be used inside the App Directory."
describe('middleware', () => {
const { next } = nextTestSetup({
files: baseFilesWith({
'middleware.ts': new FileRef(
join(fixturesDir, 'middleware', 'middleware.ts')
),
}),
skipStart: true,
skipDeployment: true,
})
it('should error when next/root-params is imported from middleware', async () => {
const { exitCode, cliOutput } = await next.build()
expect(exitCode).toBe(1)
expect(cliOutput).toContain(expectedError)
})
})
describe('instrumentation', () => {
const { next } = nextTestSetup({
files: baseFilesWith({
'instrumentation.ts': new FileRef(
join(fixturesDir, 'instrumentation', 'instrumentation.ts')
),
}),
skipStart: true,
skipDeployment: true,
})
it('should error when next/root-params is imported from instrumentation', async () => {
const { exitCode, cliOutput } = await next.build()
expect(exitCode).toBe(1)
expect(cliOutput).toContain(expectedError)
})
})
})
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