Unverified Commit 6e2c3821 authored by Damien Simonin Feugas's avatar Damien Simonin Feugas Committed by GitHub

feat: build edge functions with node.js modules and fail at runtime (#38234)

## What's in there?

The Edge runtime [does not support Node.js modules](https://edge-runtime.vercel.app/features/available-apis#unsupported-apis).
When building Next.js application, we currently fail the build when detecting node.js module imported from middleware.

This is an blocker for using code that is conditionally loading node.js modules (based on platform/env detection), as @cramforce reported.

This PR implements a new strategy where:
- we can build such middleware/Edge API route code **with a warning**
- we fail at run time, with graceful errors in dev (console & react-dev-overlay error)
- we fail at run time, with console errors in production

## How to test?

All cases are covered with integration tests.
To try them live, create a simple app with a page, a `middleware.js` file and a `pages/api/route.js`file.
Here are iconic examples:

### node.js modules
```js
// middleware.js
import { NextResponse } from 'next/server'
// static
import { basename } from 'path'

export default async function middleware() {
  // dynamic
  const { basename } = await import('path')
  basename()
  return NextResponse.next()
}

export const config = { matcher: '/' }
```
```js
// pags/api/route.js
// static
import { isAbsolute } from 'path'

export default async function handle() {
  // dynamic
  const { isAbsolute } = await import('path')
  return Response.json({ useNodeModule: isAbsolute('/test') })
}

export const config = { runtime: 'experimental-edge' }
```

Desired error (+ source code highlight in dev):

> The edge runtime does not support Node.js 'path' module
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime

Desired warning at build time:

> A Node.js module is loaded ('path' at line 2) which is not supported in the Edge Runtime.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime

- [x]  in dev middleware, static, shows desired error on stderr
- [x]  in dev route, static, shows desired error on stderr
- [x]  in dev middleware, dynamic, shows desired error on stderr
- [x]  in dev route, dynamic, shows desired error on stderr
- [x]  in dev middleware, static, shows desired error on react error overlay
- [x]  in dev route, static, shows desired error on react error overlay
- [x]  in dev middleware, dynamic, shows desired error on react error overlay
- [x]  in dev route, dynamic, shows desired error on react error overlay
- [x]  builds middleware successfully, shows build warning, shows desired error on stderr on call
- [x]  builds route successfully, shows build warning, shows desired error on stderr on call

### 3rd party modules not found

```js
// middleware.js
import { NextResponse } from 'next/server'
// static
import Unknown from 'unknown'

export default async function middleware() {
  // dynamic
  const Unknown = await import('unknown')
  new Unknown()
  return NextResponse.next()
}
```
export const config = { matcher: '/' }
```
```js
// pags/api/route.js
// static
import Unknown from 'unknown'

export default async function handle() {
  // dynamic
  const Unknown = await import('unknown')
  return Response.json({ use3rdPartyModule: Unknown() })
}

export const config = { runtime: 'experimental-edge' }
```

Desired error (+ source code highlight in dev):

> Module not found: Can't resolve 'does-not-exist'
Learn More: https://nextjs.org/docs/messages/module-not-found

- [x]  in dev middleware, static, shows desired error on stderr
- [x]  in dev route, static, shows desired error on stderr
- [x]  in dev middleware, dynamic, shows desired error on stderr
- [x]  in dev route, dynamic, shows desired error on stderr
- [x]  in dev middleware, static, shows desired error on react error overlay
- [x]  in dev route, static, shows desired error on react error overlay
- [x]  in dev middleware, dynamic, shows desired error on react error overlay
- [x]  in dev route, dynamic, shows desired error on react error overlay
- [x]  fails to build middleware, with desired error on stderr
- [x]  fails to build route, with desired error on stderr

### unused node.js modules
```js
// middleware.js
import { NextResponse } from 'next/server'

export default async function middleware() {
  if (process.exit) {
    const { basename } = await import('path')
    basename()
  }
  return NextResponse.next()
}
```
```js
// pags/api/route.js
export default async function handle() {
  if (process.exit) {
    const { basename } = await import('path')
    basename()
  }
  return Response.json({ useNodeModule: false })
}

export const config = { runtime: 'experimental-edge' }
```

Desired warning at build time:

> A Node.js module is loaded ('path' at line 2) which is not supported in the Edge Runtime.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime

- [x]  invoke middleware in dev with no error
- [x]  invoke route in dev with no error
- [x]  builds successfully, shows build warning, invoke middleware with no error
- [x]  builds successfully, shows build warning, invoke api-route with no error

## Notes to reviewers

The strategy to implement this feature is to leverages webpack [externals](https://webpack.js.org/configuration/externals/#externals) and run a global `__unsupported_module()` function when using a node.js module from edge function's code.
For the record, I tried using [webpack resolve.fallback](https://webpack.js.org/configuration/resolve/#resolvefallback) and [Webpack.IgnorePlugin](https://webpack.js.org/plugins/ignore-plugin/) but they do not allow throwing proper errors at runtime that would contain the loaded module name for reporting.

`__unsupported_module()` is defined in `EdgeRuntime`, and returns a proxy that's throw on use (whether it's property access, function call, new operator... synchronous & promise-based styles).

However there's an issue with error reporting: webpack does not includes the import lines in the generated sourcemaps, preventing from displaying useful errors.
I extended our middleware-plugin to supplement the sourcemaps (when analyzing edge function code, it saves which module is imported from which file, together with line/column/source)

The react-dev-overlay was adapted to look for this additional information when the caught error relates to modules, instead of looking at sourcemaps.

I removed the previous mechanism (built by @nkzawa ) which caught webpack errors at built time to change the displayed error message (files `next/build/index.js`, `next/build/utils.ts` and `wellknown-errors-plugin`)
parent 0f4333a5
...@@ -707,6 +707,10 @@ ...@@ -707,6 +707,10 @@
{ {
"title": "middleware-dynamic-wasm-compilation", "title": "middleware-dynamic-wasm-compilation",
"path": "/errors/middleware-dynamic-wasm-compilation.md" "path": "/errors/middleware-dynamic-wasm-compilation.md"
},
{
"title": "node-module-in-edge-runtime",
"path": "/errors/node-module-in-edge-runtime.md"
} }
] ]
} }
......
# Using Node.js module in Edge runtime
#### Why This Error Occurred
The code in your [Middleware][middleware] or your [Edge API routes][routes] is using a feature from Node.js runtime.
However, the Edge Runtime does not support [Node.js APIs and globals][node-primitives].
#### Possible Ways to Fix It
When it runs in dev mode, your application will show in the console, and in your browser, which file is importing and using an unsupported module.
This module must be avoided: either by not importing it, or by replacing it with a polyfill.
Please note your code can import Node.js modules **as long as they are not used**.
The following example builds and works at runtime:
```ts
import { NextResponse } from 'next/server'
import { spawn } from 'child_process'
export default async function middleware() {
if (process.version) {
spawn('ls', ['-lh'])
}
return NextResponse.next()
}
```
Dynamic imports in unreachable code path is also supported.
### Useful Links
- [Edge runtime supported APIs and primitives][edge-primitives]
- [Next.js Middleware][middleware]
[middleware]: https://nextjs.org/docs/advanced-features/middleware
[routes]: https://nextjs.org/docs/api-routes/edge-api-routes
[node-primitives]: https://nodejs.org/api/index.html
[edge-primitives]: https://edge-runtime.vercel.app/features/available-apis
...@@ -482,8 +482,8 @@ export function finalizeEntrypoint({ ...@@ -482,8 +482,8 @@ export function finalizeEntrypoint({
? { import: value } ? { import: value }
: value : value
const isApi = name.startsWith('pages/api/')
if (compilerType === 'server') { if (compilerType === 'server') {
const isApi = name.startsWith('pages/api/')
return { return {
publicPath: isApi ? '' : undefined, publicPath: isApi ? '' : undefined,
runtime: isApi ? 'webpack-api-runtime' : 'webpack-runtime', runtime: isApi ? 'webpack-api-runtime' : 'webpack-runtime',
...@@ -494,7 +494,7 @@ export function finalizeEntrypoint({ ...@@ -494,7 +494,7 @@ export function finalizeEntrypoint({
if (compilerType === 'edge-server') { if (compilerType === 'edge-server') {
return { return {
layer: isMiddlewareFilename(name) ? 'middleware' : undefined, layer: isMiddlewareFilename(name) || isApi ? 'middleware' : undefined,
library: { name: ['_ENTRIES', `middleware_[name]`], type: 'assign' }, library: { name: ['_ENTRIES', `middleware_[name]`], type: 'assign' },
runtime: EDGE_RUNTIME_WEBPACK, runtime: EDGE_RUNTIME_WEBPACK,
asyncChunks: false, asyncChunks: false,
......
...@@ -90,8 +90,6 @@ import { ...@@ -90,8 +90,6 @@ import {
PageInfo, PageInfo,
printCustomRoutes, printCustomRoutes,
printTreeView, printTreeView,
getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage,
getUnresolvedModuleFromError,
copyTracedFiles, copyTracedFiles,
isReservedPage, isReservedPage,
isServerComponentPage, isServerComponentPage,
...@@ -874,20 +872,6 @@ export default async function build( ...@@ -874,20 +872,6 @@ export default async function build(
console.error(error) console.error(error)
console.error() console.error()
const edgeRuntimeErrors = result.stats[2]?.compilation.errors ?? []
for (const err of edgeRuntimeErrors) {
// When using the web runtime, common Node.js native APIs are not available.
const moduleName = getUnresolvedModuleFromError(err.message)
if (!moduleName) continue
const e = new Error(
getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage(moduleName)
) as NextError
e.code = 'EDGE_RUNTIME_UNSUPPORTED_API'
throw e
}
if ( if (
error.indexOf('private-next-pages') > -1 || error.indexOf('private-next-pages') > -1 ||
error.indexOf('__next_polyfill__') > -1 error.indexOf('__next_polyfill__') > -1
......
import type { import type { NextConfigComplete, ServerRuntime } from '../server/config-shared'
NextConfig,
NextConfigComplete,
ServerRuntime,
} from '../server/config-shared'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import '../server/node-polyfill-fetch' import '../server/node-polyfill-fetch'
import chalk from 'next/dist/compiled/chalk' import chalk from 'next/dist/compiled/chalk'
...@@ -26,7 +21,6 @@ import { ...@@ -26,7 +21,6 @@ import {
MIDDLEWARE_FILENAME, MIDDLEWARE_FILENAME,
SERVER_RUNTIME, SERVER_RUNTIME,
} from '../lib/constants' } from '../lib/constants'
import { EDGE_RUNTIME_WEBPACK } from '../shared/lib/constants'
import prettyBytes from '../lib/pretty-bytes' import prettyBytes from '../lib/pretty-bytes'
import { getRouteRegex } from '../shared/lib/router/utils/route-regex' import { getRouteRegex } from '../shared/lib/router/utils/route-regex'
import { getRouteMatcher } from '../shared/lib/router/utils/route-matcher' import { getRouteMatcher } from '../shared/lib/router/utils/route-matcher'
...@@ -47,9 +41,7 @@ import { Sema } from 'next/dist/compiled/async-sema' ...@@ -47,9 +41,7 @@ import { Sema } from 'next/dist/compiled/async-sema'
import { MiddlewareManifest } from './webpack/plugins/middleware-plugin' import { MiddlewareManifest } from './webpack/plugins/middleware-plugin'
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path' import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { getPageStaticInfo } from './analysis/get-page-static-info'
const { builtinModules } = require('module')
const RESERVED_PAGE = /^\/(_app|_error|_document|api(\/|$))/ const RESERVED_PAGE = /^\/(_app|_error|_document|api(\/|$))/
const fileGzipStats: { [k: string]: Promise<number> | undefined } = {} const fileGzipStats: { [k: string]: Promise<number> | undefined } = {}
const fsStatGzip = (file: string) => { const fsStatGzip = (file: string) => {
...@@ -1120,16 +1112,6 @@ export function isServerComponentPage( ...@@ -1120,16 +1112,6 @@ export function isServerComponentPage(
}) })
} }
export function getUnresolvedModuleFromError(
error: string
): string | undefined {
const moduleErrorRegex = new RegExp(
`Module not found: Error: Can't resolve '(\\w+)'`
)
const [, moduleName] = error.match(moduleErrorRegex) || []
return builtinModules.find((item: string) => item === moduleName)
}
export async function copyTracedFiles( export async function copyTracedFiles(
dir: string, dir: string,
distDir: string, distDir: string,
...@@ -1268,49 +1250,6 @@ export function isCustomErrorPage(page: string) { ...@@ -1268,49 +1250,6 @@ export function isCustomErrorPage(page: string) {
return page === '/404' || page === '/500' return page === '/404' || page === '/500'
} }
// FIX ME: it does not work for non-middleware edge functions
// since chunks don't contain runtime specified somehow
export async function isEdgeRuntimeCompiled(
compilation: webpack5.Compilation,
module: any,
config: NextConfig
) {
if (!module) return false
for (const chunk of compilation.chunkGraph.getModuleChunksIterable(module)) {
let runtimes: string[]
if (typeof chunk.runtime === 'string') {
runtimes = [chunk.runtime]
} else if (chunk.runtime) {
runtimes = [...chunk.runtime]
} else {
runtimes = []
}
if (runtimes.some((r) => r === EDGE_RUNTIME_WEBPACK)) {
return true
}
}
const staticInfo = await getPageStaticInfo({
pageFilePath: module.resource,
nextConfig: config,
})
// Check the page runtime as well since we cannot detect the runtime from
// compilation when it's for the client part of edge function
return staticInfo.runtime === SERVER_RUNTIME.edge
}
export function getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage(
name: string
) {
return (
`You're using a Node.js module (${name}) which is not supported in the Edge Runtime.\n` +
'Learn more: https://nextjs.org/docs/api-reference/edge-runtime'
)
}
export function isMiddlewareFile(file: string) { export function isMiddlewareFile(file: string) {
return ( return (
file === `/${MIDDLEWARE_FILENAME}` || file === `/src/${MIDDLEWARE_FILENAME}` file === `/${MIDDLEWARE_FILENAME}` || file === `/src/${MIDDLEWARE_FILENAME}`
......
...@@ -34,7 +34,9 @@ import { NextConfigComplete } from '../server/config-shared' ...@@ -34,7 +34,9 @@ import { NextConfigComplete } from '../server/config-shared'
import { finalizeEntrypoint } from './entries' import { finalizeEntrypoint } from './entries'
import * as Log from './output/log' import * as Log from './output/log'
import { build as buildConfiguration } from './webpack/config' import { build as buildConfiguration } from './webpack/config'
import MiddlewarePlugin from './webpack/plugins/middleware-plugin' import MiddlewarePlugin, {
handleWebpackExtenalForEdgeRuntime,
} from './webpack/plugins/middleware-plugin'
import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin' import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin'
import { JsConfigPathsPlugin } from './webpack/plugins/jsconfig-paths-plugin' import { JsConfigPathsPlugin } from './webpack/plugins/jsconfig-paths-plugin'
import { DropClientPage } from './webpack/plugins/next-drop-client-page-plugin' import { DropClientPage } from './webpack/plugins/next-drop-client-page-plugin'
...@@ -976,6 +978,7 @@ export default async function getBaseWebpackConfig( ...@@ -976,6 +978,7 @@ export default async function getBaseWebpackConfig(
'next/dist/compiled/chalk': '{}', 'next/dist/compiled/chalk': '{}',
'react-dom': '{}', 'react-dom': '{}',
}, },
handleWebpackExtenalForEdgeRuntime,
] ]
: []), : []),
] ]
...@@ -1672,7 +1675,7 @@ export default async function getBaseWebpackConfig( ...@@ -1672,7 +1675,7 @@ export default async function getBaseWebpackConfig(
isLikeServerless, isLikeServerless,
}) })
})(), })(),
new WellKnownErrorsPlugin({ config }), new WellKnownErrorsPlugin(),
isClient && isClient &&
new CopyFilePlugin({ new CopyFilePlugin({
filePath: require.resolve('./polyfills/polyfill-nomodule'), filePath: require.resolve('./polyfills/polyfill-nomodule'),
......
...@@ -13,6 +13,7 @@ export function getModuleBuildInfo(webpackModule: webpack5.Module) { ...@@ -13,6 +13,7 @@ export function getModuleBuildInfo(webpackModule: webpack5.Module) {
nextWasmMiddlewareBinding?: WasmBinding nextWasmMiddlewareBinding?: WasmBinding
usingIndirectEval?: boolean | Set<string> usingIndirectEval?: boolean | Set<string>
route?: RouteMeta route?: RouteMeta
importLocByPath?: Map<string, any>
} }
} }
......
...@@ -96,6 +96,18 @@ export default class MiddlewarePlugin { ...@@ -96,6 +96,18 @@ export default class MiddlewarePlugin {
} }
} }
export async function handleWebpackExtenalForEdgeRuntime({
request,
contextInfo,
}: {
request: string
contextInfo: any
}) {
if (contextInfo.issuerLayer === 'middleware' && isNodeJsModule(request)) {
return `root __import_unsupported('${request}')`
}
}
function getCodeAnalizer(params: { function getCodeAnalizer(params: {
dev: boolean dev: boolean
compiler: webpack5.Compiler compiler: webpack5.Compiler
...@@ -256,12 +268,13 @@ function getCodeAnalizer(params: { ...@@ -256,12 +268,13 @@ function getCodeAnalizer(params: {
!isNullLiteral(firstParameter) && !isNullLiteral(firstParameter) &&
!isUndefinedIdentifier(firstParameter) !isUndefinedIdentifier(firstParameter)
) { ) {
const error = new wp.WebpackError( const error = buildWebpackError({
`Your middleware is returning a response body (line: ${node.loc.start.line}), which is not supported. Learn more: https://nextjs.org/docs/messages/returning-response-body-in-middleware` message: `Middleware is returning a response body (line: ${node.loc.start.line}), which is not supported.
) Learn more: https://nextjs.org/docs/messages/returning-response-body-in-middleware`,
error.name = NAME compilation,
error.module = parser.state.current parser,
error.loc = node.loc ...node,
})
if (dev) { if (dev) {
compilation.warnings.push(error) compilation.warnings.push(error)
} else { } else {
...@@ -270,6 +283,40 @@ function getCodeAnalizer(params: { ...@@ -270,6 +283,40 @@ function getCodeAnalizer(params: {
} }
} }
/**
* Handler to store original source location of static and dynamic imports into module's buildInfo.
*/
const handleImport = (node: any) => {
if (isInMiddlewareLayer(parser) && node.source?.value && node?.loc) {
const { module, source } = parser.state
const buildInfo = getModuleBuildInfo(module)
if (!buildInfo.importLocByPath) {
buildInfo.importLocByPath = new Map()
}
const importedModule = node.source.value?.toString()!
buildInfo.importLocByPath.set(importedModule, {
sourcePosition: {
...node.loc.start,
source: module.identifier(),
},
sourceContent: source.toString(),
})
if (!dev && isNodeJsModule(importedModule)) {
compilation.warnings.push(
buildWebpackError({
message: `A Node.js module is loaded ('${importedModule}' at line ${node.loc.start.line}) which is not supported in the Edge Runtime.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime`,
compilation,
parser,
...node,
})
)
}
}
}
/** /**
* A noop handler to skip analyzing some cases. * A noop handler to skip analyzing some cases.
* Order matters: for it to work, it must be registered first * Order matters: for it to work, it must be registered first
...@@ -295,6 +342,8 @@ function getCodeAnalizer(params: { ...@@ -295,6 +342,8 @@ function getCodeAnalizer(params: {
hooks.new.for('NextResponse').tap(NAME, handleNewResponseExpression) hooks.new.for('NextResponse').tap(NAME, handleNewResponseExpression)
hooks.callMemberChain.for('process').tap(NAME, handleCallMemberChain) hooks.callMemberChain.for('process').tap(NAME, handleCallMemberChain)
hooks.expressionMemberChain.for('process').tap(NAME, handleCallMemberChain) hooks.expressionMemberChain.for('process').tap(NAME, handleCallMemberChain)
hooks.importCall.tap(NAME, handleImport)
hooks.import.tap(NAME, handleImport)
/** /**
* Support static analyzing environment variables through * Support static analyzing environment variables through
...@@ -388,18 +437,19 @@ function getExtractMetadata(params: { ...@@ -388,18 +437,19 @@ function getExtractMetadata(params: {
continue continue
} }
const error = new wp.WebpackError( compilation.errors.push(
`Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Middleware ${entryName}${ buildWebpackError({
typeof buildInfo.usingIndirectEval !== 'boolean' message: `Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Middleware ${entryName}${
? `\nUsed by ${Array.from(buildInfo.usingIndirectEval).join( typeof buildInfo.usingIndirectEval !== 'boolean'
', ' ? `\nUsed by ${Array.from(buildInfo.usingIndirectEval).join(
)}` ', '
: '' )}`
}` : ''
}`,
entryModule,
compilation,
})
) )
error.module = entryModule
compilation.errors.push(error)
} }
/** /**
...@@ -564,14 +614,18 @@ function registerUnsupportedApiHooks( ...@@ -564,14 +614,18 @@ function registerUnsupportedApiHooks(
parser: webpack5.javascript.JavascriptParser, parser: webpack5.javascript.JavascriptParser,
compilation: webpack5.Compilation compilation: webpack5.Compilation
) { ) {
const { WebpackError } = compilation.compiler.webpack
for (const expression of EDGE_UNSUPPORTED_NODE_APIS) { for (const expression of EDGE_UNSUPPORTED_NODE_APIS) {
const warnForUnsupportedApi = (node: any) => { const warnForUnsupportedApi = (node: any) => {
if (!isInMiddlewareLayer(parser)) { if (!isInMiddlewareLayer(parser)) {
return return
} }
compilation.warnings.push( compilation.warnings.push(
makeUnsupportedApiError(WebpackError, parser, expression, node.loc) buildUnsupportedApiError({
compilation,
parser,
apiName: expression,
...node,
})
) )
return true return true
} }
...@@ -590,12 +644,12 @@ function registerUnsupportedApiHooks( ...@@ -590,12 +644,12 @@ function registerUnsupportedApiHooks(
return return
} }
compilation.warnings.push( compilation.warnings.push(
makeUnsupportedApiError( buildUnsupportedApiError({
WebpackError, compilation,
parser, parser,
`process.${callee}`, apiName: `process.${callee}`,
node.loc ...node,
) })
) )
return true return true
} }
...@@ -608,18 +662,43 @@ function registerUnsupportedApiHooks( ...@@ -608,18 +662,43 @@ function registerUnsupportedApiHooks(
.tap(NAME, warnForUnsupportedProcessApi) .tap(NAME, warnForUnsupportedProcessApi)
} }
function makeUnsupportedApiError( function buildUnsupportedApiError({
WebpackError: typeof webpack5.WebpackError, apiName,
parser: webpack5.javascript.JavascriptParser, loc,
name: string, ...rest
}: {
apiName: string
loc: any loc: any
) { compilation: webpack5.Compilation
const error = new WebpackError( parser: webpack5.javascript.JavascriptParser
`You're using a Node.js API (${name} at line: ${loc.start.line}) which is not supported in the Edge Runtime that Middleware uses. }) {
Learn more: https://nextjs.org/docs/api-reference/edge-runtime` return buildWebpackError({
) message: `A Node.js API is used (${apiName} at line: ${loc.start.line}) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime`,
loc,
...rest,
})
}
function buildWebpackError({
message,
loc,
compilation,
entryModule,
parser,
}: {
message: string
loc?: any
compilation: webpack5.Compilation
entryModule?: webpack5.Module
parser?: webpack5.javascript.JavascriptParser
}) {
const error = new compilation.compiler.webpack.WebpackError(message)
error.name = NAME error.name = NAME
error.module = parser.state.current const module = entryModule ?? parser?.state.current
if (module) {
error.module = module
}
error.loc = loc error.loc = loc
return error return error
} }
...@@ -653,3 +732,7 @@ function isProcessEnvMemberExpression(memberExpression: any): boolean { ...@@ -653,3 +732,7 @@ function isProcessEnvMemberExpression(memberExpression: any): boolean {
memberExpression.property.name === 'env')) memberExpression.property.name === 'env'))
) )
} }
function isNodeJsModule(moduleName: string) {
return require('module').builtinModules.includes(moduleName)
}
import type { webpack5 as webpack } from 'next/dist/compiled/webpack/webpack' import type { webpack5 as webpack } from 'next/dist/compiled/webpack/webpack'
import type { NextConfig } from '../../../../server/config-shared'
import { getModuleBuildError } from './webpackModuleError' import { getModuleBuildError } from './webpackModuleError'
const NAME = 'WellKnownErrorsPlugin'
export class WellKnownErrorsPlugin { export class WellKnownErrorsPlugin {
config: NextConfig
constructor({ config }: { config: NextConfig }) {
this.config = config
}
apply(compiler: webpack.Compiler) { apply(compiler: webpack.Compiler) {
compiler.hooks.compilation.tap('WellKnownErrorsPlugin', (compilation) => { compiler.hooks.compilation.tap(NAME, (compilation) => {
compilation.hooks.afterSeal.tapPromise( compilation.hooks.afterSeal.tapPromise(NAME, async () => {
'WellKnownErrorsPlugin', if (compilation.errors?.length) {
async () => { await Promise.all(
if (compilation.errors?.length) { compilation.errors.map(async (err, i) => {
await Promise.all( try {
compilation.errors.map(async (err, i) => { const moduleError = await getModuleBuildError(compilation, err)
try { if (moduleError !== false) {
const moduleError = await getModuleBuildError( compilation.errors[i] = moduleError
compilation,
err,
this.config
)
if (moduleError !== false) {
compilation.errors[i] = moduleError
}
} catch (e) {
console.log(e)
} }
}) } catch (e) {
) console.log(e)
} }
})
)
} }
) })
}) })
} }
} }
...@@ -2,12 +2,6 @@ import Chalk from 'next/dist/compiled/chalk' ...@@ -2,12 +2,6 @@ import Chalk from 'next/dist/compiled/chalk'
import { SimpleWebpackError } from './simpleWebpackError' import { SimpleWebpackError } from './simpleWebpackError'
import { createOriginalStackFrame } from 'next/dist/compiled/@next/react-dev-overlay/dist/middleware' import { createOriginalStackFrame } from 'next/dist/compiled/@next/react-dev-overlay/dist/middleware'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack' import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import {
getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage,
getUnresolvedModuleFromError,
isEdgeRuntimeCompiled,
} from '../../../utils'
import { NextConfig } from '../../../../server/config-shared'
const chalk = new Chalk.constructor({ enabled: true }) const chalk = new Chalk.constructor({ enabled: true })
...@@ -54,8 +48,7 @@ function getModuleTrace(input: any, compilation: any) { ...@@ -54,8 +48,7 @@ function getModuleTrace(input: any, compilation: any) {
export async function getNotFoundError( export async function getNotFoundError(
compilation: webpack5.Compilation, compilation: webpack5.Compilation,
input: any, input: any,
fileName: string, fileName: string
config: NextConfig
) { ) {
if (input.name !== 'ModuleNotFoundError') { if (input.name !== 'ModuleNotFoundError') {
return false return false
...@@ -114,15 +107,6 @@ export async function getNotFoundError( ...@@ -114,15 +107,6 @@ export async function getNotFoundError(
importTrace() + importTrace() +
'\nhttps://nextjs.org/docs/messages/module-not-found' '\nhttps://nextjs.org/docs/messages/module-not-found'
const moduleName = getUnresolvedModuleFromError(input.message)
if (moduleName) {
if (await isEdgeRuntimeCompiled(compilation, input.module, config)) {
message +=
'\n\n' +
getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage(moduleName)
}
}
return new SimpleWebpackError( return new SimpleWebpackError(
`${chalk.cyan(fileName)}:${chalk.yellow( `${chalk.cyan(fileName)}:${chalk.yellow(
result.originalStackFrame.lineNumber?.toString() ?? '' result.originalStackFrame.lineNumber?.toString() ?? ''
......
import { readFileSync } from 'fs' import { readFileSync } from 'fs'
import * as path from 'path' import * as path from 'path'
import type { webpack5 as webpack } from 'next/dist/compiled/webpack/webpack' import type { webpack5 as webpack } from 'next/dist/compiled/webpack/webpack'
import type { NextConfig } from '../../../../server/config-shared'
import { getBabelError } from './parseBabel' import { getBabelError } from './parseBabel'
import { getCssError } from './parseCss' import { getCssError } from './parseCss'
...@@ -44,8 +43,7 @@ function getFileData( ...@@ -44,8 +43,7 @@ function getFileData(
export async function getModuleBuildError( export async function getModuleBuildError(
compilation: webpack.Compilation, compilation: webpack.Compilation,
input: any, input: any
config: NextConfig
): Promise<SimpleWebpackError | false> { ): Promise<SimpleWebpackError | false> {
if ( if (
!( !(
...@@ -65,8 +63,7 @@ export async function getModuleBuildError( ...@@ -65,8 +63,7 @@ export async function getModuleBuildError(
const notFoundError = await getNotFoundError( const notFoundError = await getNotFoundError(
compilation, compilation,
input, input,
sourceFilename, sourceFilename
config
) )
if (notFoundError !== false) { if (notFoundError !== false) {
return notFoundError return notFoundError
......
...@@ -795,7 +795,10 @@ export default class DevServer extends Server { ...@@ -795,7 +795,10 @@ export default class DevServer extends Server {
if (isError(err) && err.stack) { if (isError(err) && err.stack) {
try { try {
const frames = parseStack(err.stack!) const frames = parseStack(err.stack!)
const frame = frames.find(({ file }) => !file?.startsWith('eval'))! const frame = frames.find(
({ file }) =>
!file?.startsWith('eval') && !file?.includes('sandbox/context')
)!
if (frame.lineNumber && frame?.file) { if (frame.lineNumber && frame?.file) {
const moduleId = frame.file!.replace( const moduleId = frame.file!.replace(
...@@ -803,14 +806,12 @@ export default class DevServer extends Server { ...@@ -803,14 +806,12 @@ export default class DevServer extends Server {
'' ''
) )
let compilation: any const src = getErrorSource(err as Error)
const compilation = (
const src = getErrorSource(err) src === 'edge-server'
if (src === 'edge-server') { ? this.hotReloader?.edgeServerStats?.compilation
compilation = this.hotReloader?.edgeServerStats?.compilation : this.hotReloader?.serverStats?.compilation
} else { )!
compilation = this.hotReloader?.serverStats?.compilation
}
const source = await getSourceById( const source = await getSourceById(
!!frame.file?.startsWith(sep) || !!frame.file?.startsWith('file:'), !!frame.file?.startsWith(sep) || !!frame.file?.startsWith('file:'),
...@@ -825,6 +826,8 @@ export default class DevServer extends Server { ...@@ -825,6 +826,8 @@ export default class DevServer extends Server {
frame, frame,
modulePath: moduleId, modulePath: moduleId,
rootDirectory: this.dir, rootDirectory: this.dir,
errorMessage: err.message,
compilation,
}) })
if (originalFrame) { if (originalFrame) {
......
...@@ -129,15 +129,36 @@ async function createModuleContext(options: ModuleContextOptions) { ...@@ -129,15 +129,36 @@ async function createModuleContext(options: ModuleContextOptions) {
return fn() return fn()
} }
context.__import_unsupported = function __import_unsupported(
moduleName: string
) {
const proxy: any = new Proxy(function () {}, {
get(_obj, prop) {
if (prop === 'then') {
return {}
}
throw new Error(getUnsupportedModuleErrorMessage(moduleName))
},
construct() {
throw new Error(getUnsupportedModuleErrorMessage(moduleName))
},
apply(_target, _this, args) {
if (args[0] instanceof Function) {
return args[0](proxy)
}
throw new Error(getUnsupportedModuleErrorMessage(moduleName))
},
})
return new Proxy({}, { get: () => proxy })
}
context.__next_webassembly_compile__ = context.__next_webassembly_compile__ =
function __next_webassembly_compile__(fn: Function) { function __next_webassembly_compile__(fn: Function) {
const key = fn.toString() const key = fn.toString()
if (!warnedWasmCodegens.has(key)) { if (!warnedWasmCodegens.has(key)) {
const warning = getServerError( const warning = getServerError(
new Error( new Error(`Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Middleware.
"Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Middleware.\n" + Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation`),
'Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation'
),
'edge-server' 'edge-server'
) )
warning.name = 'DynamicWasmCodeGenerationWarning' warning.name = 'DynamicWasmCodeGenerationWarning'
...@@ -163,10 +184,8 @@ async function createModuleContext(options: ModuleContextOptions) { ...@@ -163,10 +184,8 @@ async function createModuleContext(options: ModuleContextOptions) {
const key = fn.toString() const key = fn.toString()
if (instantiatedFromBuffer && !warnedWasmCodegens.has(key)) { if (instantiatedFromBuffer && !warnedWasmCodegens.has(key)) {
const warning = getServerError( const warning = getServerError(
new Error( new Error(`Dynamic WASM code generation ('WebAssembly.instantiate' with a buffer parameter) not allowed in Middleware.
"Dynamic WASM code generation ('WebAssembly.instantiate' with a buffer parameter) not allowed in Middleware.\n" + Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation`),
'Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation'
),
'edge-server' 'edge-server'
) )
warning.name = 'DynamicWasmCodeGenerationWarning' warning.name = 'DynamicWasmCodeGenerationWarning'
...@@ -321,7 +340,7 @@ function emitWarning( ...@@ -321,7 +340,7 @@ function emitWarning(
) { ) {
if (!warnedAlready.has(name)) { if (!warnedAlready.has(name)) {
const warning = const warning =
new Error(`You're using a Node.js API (${name}) which is not supported in the Edge Runtime that Middleware uses. new Error(`A Node.js API is used (${name}) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime`) Learn more: https://nextjs.org/docs/api-reference/edge-runtime`)
warning.name = 'NodejsRuntimeApiInMiddlewareWarning' warning.name = 'NodejsRuntimeApiInMiddlewareWarning'
contextOptions.onWarning(warning) contextOptions.onWarning(warning)
...@@ -335,3 +354,9 @@ function decorateUnhandledError(error: any) { ...@@ -335,3 +354,9 @@ function decorateUnhandledError(error: any) {
decorateServerError(error, 'edge-server') decorateServerError(error, 'edge-server')
} }
} }
function getUnsupportedModuleErrorMessage(module: string) {
// warning: if you change these messages, you must adjust how react-dev-overlay's middleware detects modules not found
return `The edge runtime does not support Node.js '${module}' module.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime`
}
...@@ -23,7 +23,8 @@ export async function getErrorByType( ...@@ -23,7 +23,8 @@ export async function getErrorByType(
error: event.reason, error: event.reason,
frames: await getOriginalStackFrames( frames: await getOriginalStackFrames(
event.frames, event.frames,
getErrorSource(event.reason) getErrorSource(event.reason),
event.reason.toString()
), ),
} }
} }
......
...@@ -37,7 +37,7 @@ export function getServerError(error: Error, type: ErrorType): Error { ...@@ -37,7 +37,7 @@ export function getServerError(error: Error, type: ErrorType): Error {
n.name = error.name n.name = error.name
try { try {
n.stack = parse(error.stack!) n.stack = `${n.toString()}\n${parse(error.stack!)
.map(getFilesystemFrame) .map(getFilesystemFrame)
.map((f) => { .map((f) => {
let str = ` at ${f.methodName}` let str = ` at ${f.methodName}`
...@@ -53,7 +53,7 @@ export function getServerError(error: Error, type: ErrorType): Error { ...@@ -53,7 +53,7 @@ export function getServerError(error: Error, type: ErrorType): Error {
} }
return str return str
}) })
.join('\n') .join('\n')}`
} catch { } catch {
n.stack = error.stack n.stack = error.stack
} }
......
...@@ -32,19 +32,24 @@ export type OriginalStackFrame = ...@@ -32,19 +32,24 @@ export type OriginalStackFrame =
export function getOriginalStackFrames( export function getOriginalStackFrames(
frames: StackFrame[], frames: StackFrame[],
type: 'server' | 'edge-server' | null type: 'server' | 'edge-server' | null,
errorMessage: string
) { ) {
return Promise.all(frames.map((frame) => getOriginalStackFrame(frame, type))) return Promise.all(
frames.map((frame) => getOriginalStackFrame(frame, type, errorMessage))
)
} }
export function getOriginalStackFrame( export function getOriginalStackFrame(
source: StackFrame, source: StackFrame,
type: 'server' | 'edge-server' | null type: 'server' | 'edge-server' | null,
errorMessage: string
): Promise<OriginalStackFrame> { ): Promise<OriginalStackFrame> {
async function _getOriginalStackFrame(): Promise<OriginalStackFrame> { async function _getOriginalStackFrame(): Promise<OriginalStackFrame> {
const params = new URLSearchParams() const params = new URLSearchParams()
params.append('isServer', String(type === 'server')) params.append('isServer', String(type === 'server'))
params.append('isEdgeServer', String(type === 'edge-server')) params.append('isEdgeServer', String(type === 'edge-server'))
params.append('errorMessage', errorMessage)
for (const key in source) { for (const key in source) {
params.append(key, ((source as any)[key] ?? '').toString()) params.append(key, ((source as any)[key] ?? '').toString())
} }
......
...@@ -40,6 +40,20 @@ function getModuleId(compilation: any, module: any) { ...@@ -40,6 +40,20 @@ function getModuleId(compilation: any, module: any) {
return compilation.chunkGraph.getModuleId(module) return compilation.chunkGraph.getModuleId(module)
} }
function getModuleById(
id: string | undefined,
compilation: webpack.Compilation
) {
return [...compilation.modules].find(
(searchModule) => getModuleId(compilation, searchModule) === id
)
}
function findModuleNotFoundFromError(errorMessage: string | undefined) {
const match = errorMessage?.match(/'([^']+)' module/)
return match && match[1]
}
function getModuleSource(compilation: any, module: any): any { function getModuleSource(compilation: any, module: any): any {
return ( return (
(module && (module &&
...@@ -100,6 +114,15 @@ async function findOriginalSourcePositionAndContent( ...@@ -100,6 +114,15 @@ async function findOriginalSourcePositionAndContent(
} }
} }
function findOriginalSourcePositionAndContentFromCompilation(
modulePath: string | undefined,
importedModule: string,
compilation: webpack.Compilation
) {
const module = getModuleById(modulePath, compilation)
return module?.buildInfo?.importLocByPath?.get(importedModule) ?? null
}
export async function createOriginalStackFrame({ export async function createOriginalStackFrame({
line, line,
column, column,
...@@ -107,6 +130,8 @@ export async function createOriginalStackFrame({ ...@@ -107,6 +130,8 @@ export async function createOriginalStackFrame({
modulePath, modulePath,
rootDirectory, rootDirectory,
frame, frame,
errorMessage,
compilation,
}: { }: {
line: number line: number
column: number | null column: number | null
...@@ -114,11 +139,20 @@ export async function createOriginalStackFrame({ ...@@ -114,11 +139,20 @@ export async function createOriginalStackFrame({
modulePath?: string modulePath?: string
rootDirectory: string rootDirectory: string
frame: any frame: any
errorMessage?: string
compilation?: webpack.Compilation
}): Promise<OriginalStackFrameResponse | null> { }): Promise<OriginalStackFrameResponse | null> {
const result = await findOriginalSourcePositionAndContent(source, { const moduleNotFound = findModuleNotFoundFromError(errorMessage)
line, const result = moduleNotFound
column, ? findOriginalSourcePositionAndContentFromCompilation(
}) modulePath,
moduleNotFound,
compilation
)
: await findOriginalSourcePositionAndContent(source, {
line,
column,
})
if (result === null) { if (result === null) {
return null return null
...@@ -170,7 +204,7 @@ export async function createOriginalStackFrame({ ...@@ -170,7 +204,7 @@ export async function createOriginalStackFrame({
export async function getSourceById( export async function getSourceById(
isFile: boolean, isFile: boolean,
id: string, id: string,
compilation: any compilation: webpack.Compilation
): Promise<Source> { ): Promise<Source> {
if (isFile) { if (isFile) {
const fileContent: string | null = await fs const fileContent: string | null = await fs
...@@ -198,9 +232,7 @@ export async function getSourceById( ...@@ -198,9 +232,7 @@ export async function getSourceById(
return null return null
} }
const module = [...compilation.modules].find( const module = getModuleById(id, compilation)
(searchModule) => getModuleId(compilation, searchModule) === id
)
return getModuleSource(compilation, module) return getModuleSource(compilation, module)
} catch (err) { } catch (err) {
console.error(`Failed to lookup module by ID ("${id}"):`, err) console.error(`Failed to lookup module by ID ("${id}"):`, err)
...@@ -220,6 +252,7 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) { ...@@ -220,6 +252,7 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) {
const frame = query as unknown as StackFrame & { const frame = query as unknown as StackFrame & {
isEdgeServer: 'true' | 'false' isEdgeServer: 'true' | 'false'
isServer: 'true' | 'false' isServer: 'true' | 'false'
errorMessage: string | undefined
} }
if ( if (
!( !(
...@@ -239,14 +272,13 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) { ...@@ -239,14 +272,13 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) {
) )
let source: Source let source: Source
const compilation =
frame.isEdgeServer === 'true'
? options.edgeServerStats()?.compilation
: frame.isServer === 'true'
? options.serverStats()?.compilation
: options.stats()?.compilation
try { try {
const compilation =
frame.isEdgeServer === 'true'
? options.edgeServerStats()?.compilation
: frame.isServer === 'true'
? options.serverStats()?.compilation
: options.stats()?.compilation
source = await getSourceById( source = await getSourceById(
frame.file.startsWith('file:'), frame.file.startsWith('file:'),
moduleId, moduleId,
...@@ -282,6 +314,8 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) { ...@@ -282,6 +314,8 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) {
frame, frame,
modulePath: moduleId, modulePath: moduleId,
rootDirectory: options.rootDirectory, rootDirectory: options.rootDirectory,
errorMessage: frame.errorMessage,
compilation,
}) })
if (originalStackFrameResponse === null) { if (originalStackFrameResponse === null) {
......
// populated with tests
export default () => {}
export const config = { matcher: '/' }
export default async function handler(request) {
return Response.json({ ok: true })
}
export const config = { runtime: 'experimental-edge' }
This diff is collapsed.
...@@ -5,7 +5,7 @@ import { join } from 'path' ...@@ -5,7 +5,7 @@ import { join } from 'path'
describe('Middleware validation during build', () => { describe('Middleware validation during build', () => {
const appDir = join(__dirname, '..') const appDir = join(__dirname, '..')
const middlewareFile = join(appDir, 'middleware.js') const middlewareFile = join(appDir, 'middleware.js')
const middlewareError = 'Your middleware is returning a response body' const middlewareError = 'Middleware is returning a response body'
beforeEach(() => remove(join(appDir, '.next'))) beforeEach(() => remove(join(appDir, '.next')))
......
/* eslint-env jest */
import stripAnsi from 'next/dist/compiled/strip-ansi'
import { getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage } from 'next/dist/build/utils'
import fs from 'fs-extra'
import { dirname, join } from 'path'
import {
check,
fetchViaHTTP,
File,
findPort,
killApp,
launchApp,
nextBuild,
waitFor,
} from 'next-test-utils'
jest.setTimeout(1000 * 60 * 2)
const WEBPACK_BREAKING_CHANGE = 'BREAKING CHANGE:'
const context = {
appDir: join(__dirname, '../'),
buildLogs: { output: '', stdout: '', stderr: '' },
logs: { output: '', stdout: '', stderr: '' },
middleware: new File(join(__dirname, '../middleware.js')),
page: new File(join(__dirname, '../pages/index.js')),
}
describe('Middleware importing Node.js modules', () => {
function getModuleNotFound(name) {
return `Module not found: Can't resolve '${name}'`
}
function escapeLF(s) {
return s.replace(/\n/g, '\\n')
}
afterEach(() => {
context.middleware.restore()
context.page.restore()
if (context.app) {
killApp(context.app)
}
})
describe('dev mode', () => {
// restart the app for every test since the latest error is not shown sometimes
// See https://github.com/vercel/next.js/issues/36575
beforeEach(async () => {
context.logs = { output: '', stdout: '', stderr: '' }
context.appPort = await findPort()
context.app = await launchApp(context.appDir, context.appPort, {
env: { __NEXT_TEST_WITH_DEVTOOL: 1 },
onStdout(msg) {
context.logs.output += msg
context.logs.stdout += msg
},
onStderr(msg) {
context.logs.output += msg
context.logs.stderr += msg
},
})
})
it('shows the right error when importing `path` on middleware', async () => {
context.middleware.write(`
import { NextResponse } from 'next/server'
import { basename } from 'path'
export async function middleware(request) {
console.log(basename('/foo/bar/baz/asdf/quux.html'))
return NextResponse.next()
}
`)
const res = await fetchViaHTTP(context.appPort, '/')
const text = await res.text()
await waitFor(500)
const msg = getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage('path')
expect(res.status).toBe(500)
expect(context.logs.output).toContain(getModuleNotFound('path'))
expect(context.logs.output).toContain(msg)
expect(text).toContain(escapeLF(msg))
expect(stripAnsi(context.logs.output)).toContain(
"import { basename } from 'path'"
)
expect(context.logs.output).not.toContain(WEBPACK_BREAKING_CHANGE)
})
it('shows the right error when importing `child_process` on middleware', async () => {
context.middleware.write(`
import { NextResponse } from 'next/server'
import { spawn } from 'child_process'
export async function middleware(request) {
console.log(spawn('ls', ['-lh', '/usr']))
return NextResponse.next()
}
`)
const res = await fetchViaHTTP(context.appPort, '/')
const text = await res.text()
await waitFor(500)
const msg =
getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage('child_process')
expect(res.status).toBe(500)
expect(context.logs.output).toContain(getModuleNotFound('child_process'))
expect(context.logs.output).toContain(msg)
expect(text).toContain(escapeLF(msg))
expect(stripAnsi(context.logs.output)).toContain(
"import { spawn } from 'child_process'"
)
expect(context.logs.output).not.toContain(WEBPACK_BREAKING_CHANGE)
})
it('shows the right error when importing a non-node-builtin module on middleware', async () => {
context.middleware.write(`
import { NextResponse } from 'next/server'
import NotExist from 'not-exist'
export async function middleware(request) {
new NotExist()
return NextResponse.next()
}
`)
const res = await fetchViaHTTP(context.appPort, '/')
expect(res.status).toBe(500)
const text = await res.text()
await waitFor(500)
const msg =
getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage('not-exist')
expect(context.logs.output).toContain(getModuleNotFound('not-exist'))
expect(context.logs.output).not.toContain(msg)
expect(text).not.toContain(escapeLF(msg))
})
it('shows the right error when importing `child_process` on a page', async () => {
context.page.write(`
import { spawn } from 'child_process'
export default function Page() {
spawn('ls', ['-lh', '/usr'])
return <div>ok</div>
}
`)
await fetchViaHTTP(context.appPort, '/')
// Need to request twice
// See: https://github.com/vercel/next.js/issues/36387
const res = await fetchViaHTTP(context.appPort, '/')
expect(res.status).toBe(500)
const text = await res.text()
await waitFor(500)
const msg =
getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage('child_process')
expect(context.logs.output).toContain(getModuleNotFound('child_process'))
expect(context.logs.output).not.toContain(msg)
expect(text).not.toContain(escapeLF(msg))
})
it('warns about nested middleware being not allowed', async () => {
const aboutMiddleware = join(__dirname, '../pages/about/_middleware.js')
const apiMiddleware = join(__dirname, '../pages/api/_middleware.js')
await fs.ensureDir(dirname(aboutMiddleware))
await fs.ensureDir(dirname(apiMiddleware))
await fs.writeFile(aboutMiddleware, `export function middleware() {}`)
await fs.writeFile(apiMiddleware, `export function middleware() {}`)
try {
const res = await fetchViaHTTP(context.appPort, '/about')
expect(res.status).toBe(200)
await check(() => {
return context.logs.stderr.includes(
'Nested Middleware is not allowed, found:'
) &&
context.logs.stderr.includes('pages/about/_middleware') &&
context.logs.stderr.includes('pages/api/_middleware')
? 'success'
: context.logs.output
}, 'success')
} finally {
await fs.remove(aboutMiddleware)
await fs.remove(apiMiddleware)
}
})
})
describe('production mode', () => {
it('fails with the right middleware error during build', async () => {
context.middleware.write(`
import { NextResponse } from 'next/server'
import { spawn } from 'child_process'
export async function middleware(request) {
console.log(spawn('ls', ['-lh', '/usr']))
return NextResponse.next()
}
`)
const buildResult = await nextBuild(context.appDir, undefined, {
stderr: true,
stdout: true,
})
expect(buildResult.stderr).toContain(getModuleNotFound('child_process'))
expect(buildResult.stderr).toContain(
getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage('child_process')
)
expect(buildResult.stderr).not.toContain(WEBPACK_BREAKING_CHANGE)
})
it('fails with the right page error during build', async () => {
context.page.write(`
import { spawn } from 'child_process'
export default function Page() {
spawn('ls', ['-lh', '/usr'])
return <div>ok</div>
}
`)
const buildResult = await nextBuild(context.appDir, undefined, {
stderr: true,
stdout: true,
})
expect(buildResult.stderr).toContain(getModuleNotFound('child_process'))
expect(buildResult.stderr).not.toContain(
getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage('child_process')
)
})
it('fails when there is a not allowed middleware', async () => {
const aboutMiddleware = join(__dirname, '../pages/about/_middleware.js')
const apiMiddleware = join(__dirname, '../pages/api/_middleware.js')
await fs.ensureDir(dirname(aboutMiddleware))
await fs.ensureDir(dirname(apiMiddleware))
await fs.writeFile(aboutMiddleware, `export function middleware() {}`)
await fs.writeFile(apiMiddleware, `export function middleware() {}`)
const buildResult = await nextBuild(context.appDir, undefined, {
stderr: true,
stdout: true,
})
await fs.remove(aboutMiddleware)
await fs.remove(apiMiddleware)
expect(buildResult.stderr).toContain(
'Nested Middleware is not allowed, found:'
)
expect(buildResult.stderr).toContain('pages/about/_middleware')
expect(buildResult.stderr).toContain('pages/api/_middleware')
})
})
})
import { NextResponse } from 'next/server'
export default function middleware() {
return NextResponse.next()
}
export default function Page() {
return <div>ok</div>
}
/* eslint-env jest */
import { join } from 'path'
import {
fetchViaHTTP,
findPort,
killApp,
launchApp,
nextBuild,
} from 'next-test-utils'
jest.setTimeout(1000 * 60 * 2)
const context = {
appDir: join(__dirname, '../'),
logs: { output: '', stdout: '', stderr: '' },
}
describe('Middleware importing Node.js modules', () => {
afterEach(() => {
if (context.app) {
killApp(context.app)
}
})
describe('dev mode', () => {
// restart the app for every test since the latest error is not shown sometimes
// See https://github.com/vercel/next.js/issues/36575
beforeEach(async () => {
context.logs = { stdout: '', stderr: '' }
context.appPort = await findPort()
context.app = await launchApp(context.appDir, context.appPort, {
env: { __NEXT_TEST_WITH_DEVTOOL: 1 },
onStdout(msg) {
context.logs.stdout += msg
},
onStderr(msg) {
context.logs.stderr += msg
},
})
})
it('warns about nested middleware being not allowed', async () => {
const res = await fetchViaHTTP(context.appPort, '/about')
expect(res.status).toBe(200)
context.logs.stderr.includes('Nested Middleware is not allowed, found:')
context.logs.stderr.includes('pages/about/_middleware')
context.logs.stderr.includes('pages/api/_middleware')
})
})
describe('production mode', () => {
it('fails when there is a not allowed middleware', async () => {
const buildResult = await nextBuild(context.appDir, undefined, {
stderr: true,
stdout: true,
})
expect(buildResult.stderr).toContain(
'Nested Middleware is not allowed, found:'
)
expect(buildResult.stderr).toContain('pages/about/_middleware')
expect(buildResult.stderr).toContain('pages/api/_middleware')
})
})
})
...@@ -36,12 +36,10 @@ describe('Middleware overriding a Node.js API', () => { ...@@ -36,12 +36,10 @@ describe('Middleware overriding a Node.js API', () => {
const res = await fetchViaHTTP(context.appPort, '/') const res = await fetchViaHTTP(context.appPort, '/')
await waitFor(500) await waitFor(500)
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(output) expect(output).toContain('A Node.js API is used (process.cwd')
.toContain(`NodejsRuntimeApiInMiddlewareWarning: You're using a Node.js API (process.cwd) which is not supported in the Edge Runtime that Middleware uses.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime`)
expect(output).toContain('fixed-value') expect(output).toContain('fixed-value')
expect(output).not.toContain('TypeError') expect(output).not.toContain('TypeError')
expect(output).not.toContain(`You're using a Node.js API (process.env)`) expect(output).not.toContain(`A Node.js API is used (process.env`)
}) })
}) })
}) })
...@@ -85,7 +85,7 @@ describe('Middleware using Node.js API', () => { ...@@ -85,7 +85,7 @@ describe('Middleware using Node.js API', () => {
expect(res.status).toBe(500) expect(res.status).toBe(500)
await check( await check(
() => () =>
output.includes(`NodejsRuntimeApiInMiddlewareWarning: You're using a Node.js API (${api}) which is not supported in the Edge Runtime that Middleware uses. output.includes(`A Node.js API is used (${api}) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime`) Learn more: https://nextjs.org/docs/api-reference/edge-runtime`)
? 'success' ? 'success'
: output, : output,
...@@ -118,7 +118,7 @@ Learn more: https://nextjs.org/docs/api-reference/edge-runtime`) ...@@ -118,7 +118,7 @@ Learn more: https://nextjs.org/docs/api-reference/edge-runtime`)
) )
)(`warns for $api during build`, ({ api, line }) => { )(`warns for $api during build`, ({ api, line }) => {
expect(buildResult.stderr) expect(buildResult.stderr)
.toContain(`You're using a Node.js API (${api} at line: ${line}) which is not supported in the Edge Runtime that Middleware uses. .toContain(`A Node.js API is used (${api} at line: ${line}) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime`) Learn more: https://nextjs.org/docs/api-reference/edge-runtime`)
}) })
}) })
......
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