Unverified Commit 9e53af8e authored by Naoyuki Kanezawa's avatar Naoyuki Kanezawa Committed by GitHub

Fix next node buildin module error message for edge runtime (#36434)

- improve the message for importing node builtin module on edge runtime
- fix to show the message on overlay of error browser with `next dev`
- fix https://github.com/vercel/next.js/issues/36237

The message is NOT shown when using edge runtime (not middleware) since I cannot find a way to detect a webpack compilation is for edge runtime.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `yarn lint`
parent c905fda5
...@@ -5,6 +5,7 @@ import { Span } from '../trace' ...@@ -5,6 +5,7 @@ import { Span } from '../trace'
export type CompilerResult = { export type CompilerResult = {
errors: webpack5.StatsError[] errors: webpack5.StatsError[]
warnings: webpack5.StatsError[] warnings: webpack5.StatsError[]
stats: webpack5.Stats | undefined
} }
function generateStats( function generateStats(
...@@ -54,6 +55,7 @@ export function runCompiler( ...@@ -54,6 +55,7 @@ export function runCompiler(
return resolve({ return resolve({
errors: [{ message: reason, details: (err as any).details }], errors: [{ message: reason, details: (err as any).details }],
warnings: [], warnings: [],
stats,
}) })
} }
return reject(err) return reject(err)
...@@ -61,7 +63,9 @@ export function runCompiler( ...@@ -61,7 +63,9 @@ export function runCompiler(
const result = webpackCloseSpan const result = webpackCloseSpan
.traceChild('webpack-generate-error-stats') .traceChild('webpack-generate-error-stats')
.traceFn(() => generateStats({ errors: [], warnings: [] }, stats)) .traceFn(() =>
generateStats({ errors: [], warnings: [], stats }, stats)
)
return resolve(result) return resolve(result)
}) })
}) })
......
...@@ -78,7 +78,7 @@ import { ...@@ -78,7 +78,7 @@ import {
eventPackageUsedInGetServerSideProps, eventPackageUsedInGetServerSideProps,
} from '../telemetry/events' } from '../telemetry/events'
import { Telemetry } from '../telemetry/storage' import { Telemetry } from '../telemetry/storage'
import { CompilerResult, runCompiler } from './compiler' import { runCompiler } from './compiler'
import { import {
createEntrypoints, createEntrypoints,
createPagesMapping, createPagesMapping,
...@@ -96,6 +96,7 @@ import { ...@@ -96,6 +96,7 @@ import {
PageInfo, PageInfo,
printCustomRoutes, printCustomRoutes,
printTreeView, printTreeView,
getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage,
getUnresolvedModuleFromError, getUnresolvedModuleFromError,
copyTracedFiles, copyTracedFiles,
isReservedPage, isReservedPage,
...@@ -135,6 +136,16 @@ export type PrerenderManifest = { ...@@ -135,6 +136,16 @@ export type PrerenderManifest = {
preview: __ApiPreviewProps preview: __ApiPreviewProps
} }
type CompilerResult = {
errors: webpack.StatsError[]
warnings: webpack.StatsError[]
stats: [
webpack.Stats | undefined,
webpack.Stats | undefined,
webpack.Stats | undefined
]
}
export default async function build( export default async function build(
dir: string, dir: string,
conf = null, conf = null,
...@@ -164,7 +175,6 @@ export default async function build( ...@@ -164,7 +175,6 @@ export default async function build(
// We enable concurrent features (Fizz-related rendering architecture) when // We enable concurrent features (Fizz-related rendering architecture) when
// using React 18 or experimental. // using React 18 or experimental.
const hasReactRoot = !!process.env.__NEXT_REACT_ROOT const hasReactRoot = !!process.env.__NEXT_REACT_ROOT
const hasConcurrentFeatures = hasReactRoot
const hasServerComponents = const hasServerComponents =
hasReactRoot && !!config.experimental.serverComponents hasReactRoot && !!config.experimental.serverComponents
...@@ -619,7 +629,11 @@ export default async function build( ...@@ -619,7 +629,11 @@ export default async function build(
ignore: [] as string[], ignore: [] as string[],
})) }))
let result: CompilerResult = { warnings: [], errors: [] } let result: CompilerResult = {
warnings: [],
errors: [],
stats: [undefined, undefined, undefined],
}
let webpackBuildStart let webpackBuildStart
let telemetryPlugin let telemetryPlugin
await (async () => { await (async () => {
...@@ -684,6 +698,7 @@ export default async function build( ...@@ -684,6 +698,7 @@ export default async function build(
result = { result = {
warnings: [...clientResult.warnings], warnings: [...clientResult.warnings],
errors: [...clientResult.errors], errors: [...clientResult.errors],
stats: [clientResult.stats, undefined, undefined],
} }
} else { } else {
const serverResult = await runCompiler(configs[1], { const serverResult = await runCompiler(configs[1], {
...@@ -704,6 +719,11 @@ export default async function build( ...@@ -704,6 +719,11 @@ export default async function build(
...serverResult.errors, ...serverResult.errors,
...(edgeServerResult?.errors || []), ...(edgeServerResult?.errors || []),
], ],
stats: [
clientResult.stats,
serverResult.stats,
edgeServerResult?.stats,
],
} }
} }
}) })
...@@ -745,14 +765,18 @@ export default async function build( ...@@ -745,14 +765,18 @@ export default async function build(
console.error(error) console.error(error)
console.error() console.error()
// When using the web runtime, common Node.js native APIs are not available. const edgeRuntimeErrors = result.stats[2]?.compilation.errors ?? []
const moduleName = getUnresolvedModuleFromError(error)
if (hasConcurrentFeatures && moduleName) { for (const err of edgeRuntimeErrors) {
const err = new Error( // When using the web runtime, common Node.js native APIs are not available.
`Native Node.js APIs are not supported in the Edge Runtime. Found \`${moduleName}\` imported.\n\n` const moduleName = getUnresolvedModuleFromError(err.message)
if (!moduleName) continue
const e = new Error(
getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage(moduleName)
) as NextError ) as NextError
err.code = 'EDGE_RUNTIME_UNSUPPORTED_API' e.code = 'EDGE_RUNTIME_UNSUPPORTED_API'
throw err throw e
} }
if ( if (
......
import createStore from 'next/dist/compiled/unistore' import createStore from 'next/dist/compiled/unistore'
import stripAnsi from 'next/dist/compiled/strip-ansi' import stripAnsi from 'next/dist/compiled/strip-ansi'
import { flushAllTraces } from '../../trace' import { flushAllTraces } from '../../trace'
import { getUnresolvedModuleFromError } from '../utils'
import * as Log from './log' import * as Log from './log'
...@@ -90,14 +89,6 @@ store.subscribe((state) => { ...@@ -90,14 +89,6 @@ store.subscribe((state) => {
} }
} }
const moduleName = getUnresolvedModuleFromError(cleanError)
if (state.hasEdgeServer && moduleName) {
console.error(
`Native Node.js APIs are not supported in the Edge Runtime. Found \`${moduleName}\` imported.\n`
)
return
}
// Ensure traces are flushed after each compile in development mode // Ensure traces are flushed after each compile in development mode
flushAllTraces() flushAllTraces()
return return
......
import type { NextConfigComplete, PageRuntime } from '../server/config-shared' import type {
NextConfig,
NextConfigComplete,
PageRuntime,
} 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'
...@@ -20,6 +25,7 @@ import { ...@@ -20,6 +25,7 @@ import {
SERVER_PROPS_SSG_CONFLICT, SERVER_PROPS_SSG_CONFLICT,
MIDDLEWARE_ROUTE, MIDDLEWARE_ROUTE,
} 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 { getRouteMatcher, getRouteRegex } from '../shared/lib/router/utils' import { getRouteMatcher, getRouteRegex } from '../shared/lib/router/utils'
import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic' import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic'
...@@ -40,6 +46,7 @@ import { Sema } from 'next/dist/compiled/async-sema' ...@@ -40,6 +46,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 { getPageRuntime } from './entries'
const { builtinModules } = require('module') const { builtinModules } = require('module')
const RESERVED_PAGE = /^\/(_app|_error|_document|api(\/|$))/ const RESERVED_PAGE = /^\/(_app|_error|_document|api(\/|$))/
...@@ -1121,7 +1128,7 @@ export function getUnresolvedModuleFromError( ...@@ -1121,7 +1128,7 @@ export function getUnresolvedModuleFromError(
error: string error: string
): string | undefined { ): string | undefined {
const moduleErrorRegex = new RegExp( const moduleErrorRegex = new RegExp(
`Module not found: Can't resolve '(\\w+)'` `Module not found: Error: Can't resolve '(\\w+)'`
) )
const [, moduleName] = error.match(moduleErrorRegex) || [] const [, moduleName] = error.match(moduleErrorRegex) || []
return builtinModules.find((item: string) => item === moduleName) return builtinModules.find((item: string) => item === moduleName)
...@@ -1264,3 +1271,41 @@ export function isReservedPage(page: string) { ...@@ -1264,3 +1271,41 @@ export function isReservedPage(page: string) {
export function isCustomErrorPage(page: string) { 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
}
}
// 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 (await getPageRuntime(module.resource, config)) === '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'
)
}
...@@ -1537,7 +1537,7 @@ export default async function getBaseWebpackConfig( ...@@ -1537,7 +1537,7 @@ export default async function getBaseWebpackConfig(
isLikeServerless, isLikeServerless,
}) })
})(), })(),
new WellKnownErrorsPlugin(), new WellKnownErrorsPlugin({ config }),
isClient && isClient &&
new CopyFilePlugin({ new CopyFilePlugin({
filePath: require.resolve('./polyfills/polyfill-nomodule'), filePath: require.resolve('./polyfills/polyfill-nomodule'),
......
import type { webpack5 as webpack } from 'next/dist/compiled/webpack/webpack' import type { webpack5 as webpack } from 'next/dist/compiled/webpack/webpack'
import { getModuleBuildError } from './webpackModuleError' import { getModuleBuildError } from './webpackModuleError'
import { NextConfig } from '../../../../server/config-shared'
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('WellKnownErrorsPlugin', (compilation) => {
compilation.hooks.afterSeal.tapPromise( compilation.hooks.afterSeal.tapPromise(
...@@ -13,7 +20,8 @@ export class WellKnownErrorsPlugin { ...@@ -13,7 +20,8 @@ export class WellKnownErrorsPlugin {
try { try {
const moduleError = await getModuleBuildError( const moduleError = await getModuleBuildError(
compilation, compilation,
err err,
this.config
) )
if (moduleError !== false) { if (moduleError !== false) {
compilation.errors[i] = moduleError compilation.errors[i] = moduleError
......
...@@ -2,6 +2,12 @@ import Chalk from 'next/dist/compiled/chalk' ...@@ -2,6 +2,12 @@ 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/middleware' import { createOriginalStackFrame } from 'next/dist/compiled/@next/react-dev-overlay/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 })
...@@ -48,7 +54,8 @@ function getModuleTrace(input: any, compilation: any) { ...@@ -48,7 +54,8 @@ 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
...@@ -98,7 +105,7 @@ export async function getNotFoundError( ...@@ -98,7 +105,7 @@ export async function getNotFoundError(
const frame = result.originalCodeFrame ?? '' const frame = result.originalCodeFrame ?? ''
const message = let message =
chalk.red.bold('Module not found') + chalk.red.bold('Module not found') +
`: ${errorMessage}` + `: ${errorMessage}` +
'\n' + '\n' +
...@@ -107,6 +114,15 @@ export async function getNotFoundError( ...@@ -107,6 +114,15 @@ 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() ?? ''
......
...@@ -7,6 +7,7 @@ import { getScssError } from './parseScss' ...@@ -7,6 +7,7 @@ import { getScssError } from './parseScss'
import { getNotFoundError } from './parseNotFoundError' import { getNotFoundError } from './parseNotFoundError'
import { SimpleWebpackError } from './simpleWebpackError' import { SimpleWebpackError } from './simpleWebpackError'
import isError from '../../../../lib/is-error' import isError from '../../../../lib/is-error'
import { NextConfig } from '../../../../server/config-shared'
function getFileData( function getFileData(
compilation: webpack.Compilation, compilation: webpack.Compilation,
...@@ -42,7 +43,8 @@ function getFileData( ...@@ -42,7 +43,8 @@ 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 (
!( !(
...@@ -62,7 +64,8 @@ export async function getModuleBuildError( ...@@ -62,7 +64,8 @@ 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
......
...@@ -163,7 +163,11 @@ function formatWebpackMessages(json, verbose) { ...@@ -163,7 +163,11 @@ function formatWebpackMessages(json, verbose) {
const formattedWarnings = json.warnings.map(function (message) { const formattedWarnings = json.warnings.map(function (message) {
return formatMessage(message, verbose) return formatMessage(message, verbose)
}) })
const result = { errors: formattedErrors, warnings: formattedWarnings } const result = {
...json,
errors: formattedErrors,
warnings: formattedWarnings,
}
if (!verbose && result.errors.some(isLikelyASyntaxError)) { if (!verbose && result.errors.some(isLikelyASyntaxError)) {
// If there are any syntax errors, show just them. // If there are any syntax errors, show just them.
result.errors = result.errors.filter(isLikelyASyntaxError) result.errors = result.errors.filter(isLikelyASyntaxError)
......
/* eslint-env jest */ /* eslint-env jest */
import stripAnsi from 'next/dist/compiled/strip-ansi' import stripAnsi from 'next/dist/compiled/strip-ansi'
import { getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage } from 'next/dist/build/utils'
import { join } from 'path' import { join } from 'path'
import { import {
fetchViaHTTP, fetchViaHTTP,
...@@ -22,14 +23,17 @@ describe('Middleware importing Node.js built-in module', () => { ...@@ -22,14 +23,17 @@ describe('Middleware importing Node.js built-in module', () => {
return `Module not found: Can't resolve '${name}'` return `Module not found: Can't resolve '${name}'`
} }
function getBuiltinApisNotSupported(name) { function escapeLF(s) {
return `Native Node.js APIs are not supported in the Edge Runtime. Found \`${name}\` imported.\n` return s.replace(/\n/g, '\\n')
} }
describe('dev mode', () => { describe('dev mode', () => {
let output = '' let output = ''
beforeAll(async () => { // 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 () => {
output = ''
context.appPort = await findPort() context.appPort = await findPort()
context.app = await launchApp(context.appDir, context.appPort, { context.app = await launchApp(context.appDir, context.appPort, {
env: { __NEXT_TEST_WITH_DEVTOOL: 1 }, env: { __NEXT_TEST_WITH_DEVTOOL: 1 },
...@@ -42,25 +46,31 @@ describe('Middleware importing Node.js built-in module', () => { ...@@ -42,25 +46,31 @@ describe('Middleware importing Node.js built-in module', () => {
}) })
}) })
beforeEach(() => (output = '')) afterEach(() => killApp(context.app))
afterAll(() => killApp(context.app))
it('shows error when importing path module', async () => { it('shows error when importing path module', async () => {
const res = await fetchViaHTTP(context.appPort, '/using-path') const res = await fetchViaHTTP(context.appPort, '/using-path')
const text = await res.text()
await waitFor(500) await waitFor(500)
const msg = getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage('path')
expect(res.status).toBe(500) expect(res.status).toBe(500)
expect(output).toContain(getModuleNotFound('path')) expect(output).toContain(getModuleNotFound('path'))
expect(output).toContain(getBuiltinApisNotSupported('path')) expect(output).toContain(msg)
expect(text).toContain(escapeLF(msg))
expect(stripAnsi(output)).toContain("import { basename } from 'path'") expect(stripAnsi(output)).toContain("import { basename } from 'path'")
expect(output).not.toContain(WEBPACK_BREAKING_CHANGE) expect(output).not.toContain(WEBPACK_BREAKING_CHANGE)
}) })
it('shows error when importing child_process module', async () => { it('shows error when importing child_process module', async () => {
const res = await fetchViaHTTP(context.appPort, '/using-child-process') const res = await fetchViaHTTP(context.appPort, '/using-child-process')
const text = await res.text()
await waitFor(500) await waitFor(500)
const msg =
getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage('child_process')
expect(res.status).toBe(500) expect(res.status).toBe(500)
expect(output).toContain(getModuleNotFound('child_process')) expect(output).toContain(getModuleNotFound('child_process'))
expect(output).toContain(getBuiltinApisNotSupported('child_process')) expect(output).toContain(msg)
expect(text).toContain(escapeLF(msg))
expect(stripAnsi(output)).toContain( expect(stripAnsi(output)).toContain(
"import { spawn } from 'child_process'" "import { spawn } from 'child_process'"
) )
...@@ -82,7 +92,7 @@ describe('Middleware importing Node.js built-in module', () => { ...@@ -82,7 +92,7 @@ describe('Middleware importing Node.js built-in module', () => {
expect(buildResult.stderr).toContain(getModuleNotFound('child_process')) expect(buildResult.stderr).toContain(getModuleNotFound('child_process'))
expect(buildResult.stderr).toContain(getModuleNotFound('path')) expect(buildResult.stderr).toContain(getModuleNotFound('path'))
expect(buildResult.stderr).toContain( expect(buildResult.stderr).toContain(
getBuiltinApisNotSupported('child_process') getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage('child_process')
) )
expect(buildResult.stderr).not.toContain(WEBPACK_BREAKING_CHANGE) expect(buildResult.stderr).not.toContain(WEBPACK_BREAKING_CHANGE)
}) })
......
import { spawn } from 'child_process'
export default function Page() {
spawn('ls', ['-lh', '/usr'])
return <div>ok</div>
}
import { NextResponse } from 'next/server'
import NotExist from 'not-exist'
export async function middleware(request) {
new NotExist()
return NextResponse.next()
}
/* eslint-env jest */
import { getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage } from 'next/dist/build/utils'
import { join } from 'path'
import {
fetchViaHTTP,
findPort,
killApp,
launchApp,
nextBuild,
waitFor,
} from 'next-test-utils'
const context = {}
jest.setTimeout(1000 * 60 * 2)
context.appDir = join(__dirname, '../')
describe('Middleware importing Node.js built-in module', () => {
function getModuleNotFound(name) {
return `Module not found: Can't resolve '${name}'`
}
function escapeLF(s) {
return s.replace(/\n/g, '\\n')
}
describe('dev mode', () => {
let output = ''
// restart the app for every test since the latest error is not shown sometimes
beforeEach(async () => {
output = ''
context.appPort = await findPort()
context.app = await launchApp(context.appDir, context.appPort, {
env: { __NEXT_TEST_WITH_DEVTOOL: 1 },
onStdout(msg) {
output += msg
},
onStderr(msg) {
output += msg
},
})
})
afterEach(() => killApp(context.app))
it('does not show the not-supported error when importing non-node-builtin module', async () => {
const res = await fetchViaHTTP(context.appPort, '/using-not-exist')
expect(res.status).toBe(500)
const text = await res.text()
await waitFor(500)
const msg =
getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage('not-exist')
expect(output).toContain(getModuleNotFound('not-exist'))
expect(output).not.toContain(msg)
expect(text).not.toContain(escapeLF(msg))
})
it('does not show the not-supported error when importing child_process module on a page', async () => {
await fetchViaHTTP(context.appPort, '/using-child-process-on-page')
// Need to request twice
// See: https://github.com/vercel/next.js/issues/36387
const res = await fetchViaHTTP(
context.appPort,
'/using-child-process-on-page'
)
expect(res.status).toBe(500)
const text = await res.text()
await waitFor(500)
const msg =
getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage('child_process')
expect(output).toContain(getModuleNotFound('child_process'))
expect(output).not.toContain(msg)
expect(text).not.toContain(escapeLF(msg))
})
})
describe('production mode', () => {
let buildResult
beforeAll(async () => {
buildResult = await nextBuild(context.appDir, undefined, {
stderr: true,
stdout: true,
})
})
it('should not have middleware error during build', () => {
expect(buildResult.stderr).toContain(getModuleNotFound('child_process'))
expect(buildResult.stderr).not.toContain(
getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage('child_process')
)
})
})
})
...@@ -25,6 +25,7 @@ import rsc from './rsc' ...@@ -25,6 +25,7 @@ import rsc from './rsc'
import streaming from './streaming' import streaming from './streaming'
import basic from './basic' import basic from './basic'
import runtime from './runtime' import runtime from './runtime'
import { getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage } from 'next/dist/build/utils'
const rscAppPage = ` const rscAppPage = `
import Container from '../components/container.server' import Container from '../components/container.server'
...@@ -52,7 +53,7 @@ export default function Page500() { ...@@ -52,7 +53,7 @@ export default function Page500() {
describe('Edge runtime - errors', () => { describe('Edge runtime - errors', () => {
it('should warn user that native node APIs are not supported', async () => { it('should warn user that native node APIs are not supported', async () => {
const fsImportedErrorMessage = const fsImportedErrorMessage =
'Native Node.js APIs are not supported in the Edge Runtime. Found `dns` imported.' getNodeBuiltinModuleNotSupportedInEdgeRuntimeMessage('dns')
const { stderr } = await nextBuild(nativeModuleTestAppDir, [], { const { stderr } = await nextBuild(nativeModuleTestAppDir, [], {
stderr: true, stderr: true,
}) })
......
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