Unverified Commit 409b2810 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

Improve Proxy invalid export error message (#84887)

Improve invalid Proxy/Middleware export error message to:

```
> Build error occurred
Error: The file "./proxy.ts" must export a function, either as a default export or as a named "proxy" export.
This function is what Next.js runs for every request handled by this proxy (previously called middleware).

Why this happens:
- You are migrating from `middleware` to `proxy`, but haven't updated the exported function.
- The file exists but doesn't export a function.
- The export is not a function (e.g., an object or constant).
- There's a syntax error preventing the export from being recognized.

To fix it:
- Ensure this file has either a default or "proxy" function export.

Learn more: https://nextjs.org/docs/messages/middleware-to-proxy
```

Turbopack:
```
Error: Turbopack build failed with 1 errors:
./proxy.ts
Proxy is missing expected function export name
This function is what Next.js runs for every request handled by this proxy (previously called middleware).

Why this happens:
- You are migrating from `middleware` to `proxy`, but haven't updated the exported function.
- The file exists but doesn't export a function.
- The export is not a function (e.g., an object or constant).
- There's a syntax error preventing the export from being recognized.

To fix it:
- Ensure this file has either a default or "proxy" function export.

Learn more: https://nextjs.org/docs/messages/middleware-to-proxy
```

Closes NEXT-4741
parent e2262334
...@@ -4322,6 +4322,7 @@ dependencies = [ ...@@ -4322,6 +4322,7 @@ dependencies = [
"next-custom-transforms", "next-custom-transforms",
"next-taskless", "next-taskless",
"once_cell", "once_cell",
"pathdiff",
"percent-encoding", "percent-encoding",
"qstring", "qstring",
"react_remove_properties", "react_remove_properties",
......
...@@ -139,23 +139,48 @@ impl Issue for MiddlewareMissingExportIssue { ...@@ -139,23 +139,48 @@ impl Issue for MiddlewareMissingExportIssue {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn title(&self) -> Vc<StyledString> { async fn title(&self) -> Result<Vc<StyledString>> {
let file_name = self.file_path.file_name(); let title_text = format!(
"{} is missing expected function export name",
StyledString::Line(vec![ self.file_type
StyledString::Text(rcstr!("The ")), );
StyledString::Code(self.file_type.clone()),
StyledString::Text(rcstr!(" file \"")), Ok(StyledString::Text(title_text.into()).cell())
StyledString::Code(format!("./{}", file_name).into()),
StyledString::Text(rcstr!("\" must export a function named ")),
StyledString::Code(format!("`{}`", self.function_name).into()),
StyledString::Text(rcstr!(" or a default function.")),
])
.cell()
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn description(&self) -> Vc<OptionStyledString> { async fn description(&self) -> Result<Vc<OptionStyledString>> {
Vc::cell(None) let type_description = if self.file_type == "Proxy" {
"proxy (previously called middleware)"
} else {
"middleware"
};
let migration_bullet = if self.file_type == "Proxy" {
"- You are migrating from `middleware` to `proxy`, but haven't updated the exported \
function.\n"
} else {
""
};
// Rest of the message goes in description to avoid formatIssue indentation
let description_text = format!(
"This function is what Next.js runs for every request handled by this {}.\n\n\
Why this happens:\n\
{}\
- The file exists but doesn't export a function.\n\
- The export is not a function (e.g., an object or constant).\n\
- There's a syntax error preventing the export from being recognized.\n\n\
To fix it:\n\
- Ensure this file has either a default or \"{}\" function export.\n\n\
Learn more: https://nextjs.org/docs/messages/middleware-to-proxy",
type_description,
migration_bullet,
self.function_name
);
Ok(Vc::cell(Some(
StyledString::Text(description_text.into()).resolved_cell(),
)))
} }
} }
...@@ -900,5 +900,6 @@ ...@@ -900,5 +900,6 @@
"899": "Both \"%s\" and \"%s\" files are detected. Please use \"%s\" instead. Learn more: https://nextjs.org/docs/messages/middleware-to-proxy", "899": "Both \"%s\" and \"%s\" files are detected. Please use \"%s\" instead. Learn more: https://nextjs.org/docs/messages/middleware-to-proxy",
"900": "Both %s file \"./%s\" and %s file \"./%s\" are detected. Please use \"./%s\" only. Learn more: https://nextjs.org/docs/messages/middleware-to-proxy", "900": "Both %s file \"./%s\" and %s file \"./%s\" are detected. Please use \"./%s\" only. Learn more: https://nextjs.org/docs/messages/middleware-to-proxy",
"901": "Invalid \"cacheHandlers\" provided, expected an object e.g. { default: '/my-handler.js' }, received %s", "901": "Invalid \"cacheHandlers\" provided, expected an object e.g. { default: '/my-handler.js' }, received %s",
"902": "Invalid handler fields configured for \"cacheHandlers\":\\n%s" "902": "Invalid handler fields configured for \"cacheHandlers\":\\n%s",
"903": "The file \"%s\" must export a function, either as a default export or as a named \"%s\" export.\\nThis function is what Next.js runs for every request handled by this %s.\\n\\nWhy this happens:\\n%s- The file exists but doesn't export a function.\\n- The export is not a function (e.g., an object or constant).\\n- There's a syntax error preventing the export from being recognized.\\n\\nTo fix it:\\n- Ensure this file has either a default or \"%s\" function export.\\n\\nLearn more: https://nextjs.org/docs/messages/middleware-to-proxy"
} }
...@@ -2,7 +2,7 @@ import type { NextConfig } from '../../server/config-shared' ...@@ -2,7 +2,7 @@ import type { NextConfig } from '../../server/config-shared'
import type { RouteHas } from '../../lib/load-custom-routes' import type { RouteHas } from '../../lib/load-custom-routes'
import { promises as fs } from 'fs' import { promises as fs } from 'fs'
import { basename } from 'path' import { relative } from 'path'
import { LRUCache } from '../../server/lib/lru-cache' import { LRUCache } from '../../server/lib/lru-cache'
import { import {
extractExportedConstValue, extractExportedConstValue,
...@@ -329,7 +329,7 @@ function validateMiddlewareProxyExports({ ...@@ -329,7 +329,7 @@ function validateMiddlewareProxyExports({
return return
} }
const fileName = isProxy ? 'proxy' : 'middleware' const fileName = isProxy ? PROXY_FILENAME : MIDDLEWARE_FILENAME
// Parse AST to get export info (since checkExports doesn't return middleware/proxy info) // Parse AST to get export info (since checkExports doesn't return middleware/proxy info)
let hasDefaultExport = false let hasDefaultExport = false
...@@ -396,9 +396,22 @@ function validateMiddlewareProxyExports({ ...@@ -396,9 +396,22 @@ function validateMiddlewareProxyExports({
(isMiddleware && hasMiddlewareExport) || (isMiddleware && hasMiddlewareExport) ||
(isProxy && hasProxyExport) (isProxy && hasProxyExport)
const relativeFilePath = `./${relative(process.cwd(), pageFilePath)}`
if (!hasValidExport) { if (!hasValidExport) {
throw new Error( throw new Error(
`The ${fileName === 'proxy' ? 'Proxy' : 'Middleware'} file "./${basename(pageFilePath)}" must export a function named \`${fileName}\` or a default function.` `The file "${relativeFilePath}" must export a function, either as a default export or as a named "${fileName}" export.\n` +
`This function is what Next.js runs for every request handled by this ${fileName === 'proxy' ? 'proxy (previously called middleware)' : 'middleware'}.\n\n` +
`Why this happens:\n` +
(isProxy
? "- You are migrating from `middleware` to `proxy`, but haven't updated the exported function.\n"
: '') +
`- The file exists but doesn't export a function.\n` +
`- The export is not a function (e.g., an object or constant).\n` +
`- There's a syntax error preventing the export from being recognized.\n\n` +
`To fix it:\n` +
`- Ensure this file has either a default or "${fileName}" function export.\n\n` +
`Learn more: https://nextjs.org/docs/messages/middleware-to-proxy`
) )
} }
} }
......
...@@ -19,8 +19,25 @@ const isProxy = page === '/proxy' || page === '/src/proxy' ...@@ -19,8 +19,25 @@ const isProxy = page === '/proxy' || page === '/src/proxy'
const handler = (isProxy ? mod.proxy : mod.middleware) || mod.default const handler = (isProxy ? mod.proxy : mod.middleware) || mod.default
if (typeof handler !== 'function') { if (typeof handler !== 'function') {
const fileName = isProxy ? 'proxy' : 'middleware'
// Webpack starts the path with "." as relative, but Turbopack does not.
const resolvedRelativeFilePath = relativeFilePath.startsWith('.')
? relativeFilePath
: `./${relativeFilePath}`
throw new Error( throw new Error(
`The ${isProxy ? 'Proxy' : 'Middleware'} file "${relativeFilePath.startsWith('.') ? relativeFilePath : `./${relativeFilePath}`}" must export a function named \`${isProxy ? 'proxy' : 'middleware'}\` or a default function.` `The file "${resolvedRelativeFilePath}" must export a function, either as a default export or as a named "${fileName}" export.\n` +
`This function is what Next.js runs for every request handled by this ${fileName === 'proxy' ? 'proxy (previously called middleware)' : 'middleware'}.\n\n` +
`Why this happens:\n` +
(isProxy
? "- You are migrating from `middleware` to `proxy`, but haven't updated the exported function.\n"
: '') +
`- The file exists but doesn't export a function.\n` +
`- The export is not a function (e.g., an object or constant).\n` +
`- There's a syntax error preventing the export from being recognized.\n\n` +
`To fix it:\n` +
`- Ensure this file has either a default or "${fileName}" function export.\n\n` +
`Learn more: https://nextjs.org/docs/messages/middleware-to-proxy`
) )
} }
......
...@@ -2,8 +2,18 @@ import { nextTestSetup } from 'e2e-utils' ...@@ -2,8 +2,18 @@ import { nextTestSetup } from 'e2e-utils'
import { join } from 'node:path' import { join } from 'node:path'
import { writeFile } from 'node:fs/promises' import { writeFile } from 'node:fs/promises'
const errorMessage = const errorMessage = `This function is what Next.js runs for every request handled by this proxy (previously called middleware).
'The Proxy file "./proxy.ts" must export a function named `proxy` or a default function.'
Why this happens:
- You are migrating from \`middleware\` to \`proxy\`, but haven't updated the exported function.
- The file exists but doesn't export a function.
- The export is not a function (e.g., an object or constant).
- There's a syntax error preventing the export from being recognized.
To fix it:
- Ensure this file has either a default or "proxy" function export.
Learn more: https://nextjs.org/docs/messages/middleware-to-proxy`
describe('proxy-missing-export', () => { describe('proxy-missing-export', () => {
const { next, isNextDev, skipped } = nextTestSetup({ const { next, isNextDev, skipped } = nextTestSetup({
...@@ -22,14 +32,26 @@ describe('proxy-missing-export', () => { ...@@ -22,14 +32,26 @@ describe('proxy-missing-export', () => {
'export function middleware() {}' 'export function middleware() {}'
) )
let cliOutput: string
if (isNextDev) { if (isNextDev) {
await next.start().catch(() => {}) await next.start().catch(() => {})
// Use .catch() because Turbopack errors during compile and exits before runtime. // Use .catch() because Turbopack errors during compile and exits before runtime.
await next.browser('/').catch(() => {}) await next.browser('/').catch(() => {})
expect(next.cliOutput).toContain(errorMessage) cliOutput = next.cliOutput
} else {
cliOutput = (await next.build()).cliOutput
}
// TODO: Investigate why in dev-turbo, the error is shown in the browser console, not CLI output.
if (process.env.IS_TURBOPACK_TEST && !isNextDev) {
expect(cliOutput).toContain(`./proxy.ts
Proxy is missing expected function export name
${errorMessage}`)
} else { } else {
const { cliOutput } = await next.build() expect(cliOutput)
expect(cliOutput).toContain(errorMessage) .toContain(`The file "./proxy.ts" must export a function, either as a default export or as a named "proxy" export.
${errorMessage}`)
} }
await next.stop() await next.stop()
...@@ -94,16 +116,27 @@ describe('proxy-missing-export', () => { ...@@ -94,16 +116,27 @@ describe('proxy-missing-export', () => {
'const proxy = () => {}; export { proxy as handler };' 'const proxy = () => {}; export { proxy as handler };'
) )
let cliOutput: string
if (isNextDev) { if (isNextDev) {
await next.start().catch(() => {}) await next.start().catch(() => {})
// Use .catch() because Turbopack errors during compile and exits before runtime. // Use .catch() because Turbopack errors during compile and exits before runtime.
await next.browser('/').catch(() => {}) await next.browser('/').catch(() => {})
expect(next.cliOutput).toContain(errorMessage) cliOutput = next.cliOutput
} else { } else {
const { cliOutput } = await next.build() cliOutput = (await next.build()).cliOutput
expect(cliOutput).toContain(errorMessage)
} }
// TODO: Investigate why in dev-turbo, the error is shown in the browser console, not CLI output.
if (process.env.IS_TURBOPACK_TEST && !isNextDev) {
expect(cliOutput).toContain(`./proxy.ts
Proxy is missing expected function export name
${errorMessage}`)
} else {
expect(cliOutput)
.toContain(`The file "./proxy.ts" must export a function, either as a default export or as a named "proxy" export.
${errorMessage}`)
}
await next.stop() await next.stop()
}) })
}) })
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