Unverified Commit d56ed7bb authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

Allow inspecting server with `next start --inspect` (#88744)

parent a1ba3d4b
...@@ -115,13 +115,16 @@ To debug server-side Next.js code with browser DevTools, you need to pass the `- ...@@ -115,13 +115,16 @@ To debug server-side Next.js code with browser DevTools, you need to pass the `-
```bash filename="Terminal" ```bash filename="Terminal"
next dev --inspect next dev --inspect
# or
next start --inspect
# next build --inspect is currently not supported
``` ```
The value of `--inspect` is passed to the underlying Node.js process. Check out the [`--inspect` docs for advanced use cases](https://nodejs.org/api/cli.html#--inspecthostport). The value of `--inspect` is passed to the underlying Node.js process. Check out the [`--inspect` docs for advanced use cases](https://nodejs.org/api/cli.html#--inspecthostport).
> **Good to know**: Use `--inspect=0.0.0.0` to allow remote debugging access outside localhost, such as when running the app in a Docker container. > **Good to know**: Use `--inspect=0.0.0.0` to allow remote debugging access outside localhost, such as when running the app in a Docker container.
Launching the Next.js dev server with the `--inspect` flag will look something like this: Launching the Next.js server with the `--inspect` flag will look something like this:
```bash filename="Terminal" ```bash filename="Terminal"
Debugger listening on ws://127.0.0.1:9229/0cf90313-350d-4466-a748-cd60f4e47c95 Debugger listening on ws://127.0.0.1:9229/0cf90313-350d-4466-a748-cd60f4e47c95
......
...@@ -88,7 +88,11 @@ class NextRootCommand extends Command { ...@@ -88,7 +88,11 @@ class NextRootCommand extends Command {
;(process.env as any).NODE_ENV = process.env.NODE_ENV || defaultEnv ;(process.env as any).NODE_ENV = process.env.NODE_ENV || defaultEnv
;(process.env as any).NEXT_RUNTIME = 'nodejs' ;(process.env as any).NEXT_RUNTIME = 'nodejs'
if (commandName !== 'dev' && event.getOptionValue('inspect') === true) { if (
commandName !== 'dev' &&
commandName !== 'start' &&
event.getOptionValue('inspect') === true
) {
console.error( console.error(
`\`--inspect\` flag is deprecated. Use env variable NODE_OPTIONS instead: NODE_OPTIONS='--inspect' next ${commandName}` `\`--inspect\` flag is deprecated. Use env variable NODE_OPTIONS instead: NODE_OPTIONS='--inspect' next ${commandName}`
) )
...@@ -380,6 +384,12 @@ program ...@@ -380,6 +384,12 @@ program
'-H, --hostname <hostname>', '-H, --hostname <hostname>',
'Specify a hostname on which to start the application (default: 0.0.0.0).' 'Specify a hostname on which to start the application (default: 0.0.0.0).'
) )
.addOption(
new Option(
'--inspect [[host:]port]',
'Allows inspecting server-side code. See https://nextjs.org/docs/app/guides/debugging#server-side-code'
).argParser(parseValidInspectAddress)
)
.addOption( .addOption(
new Option( new Option(
'--keepAliveTimeout <keepAliveTimeout>', '--keepAliveTimeout <keepAliveTimeout>',
......
...@@ -10,7 +10,12 @@ if (!process.env.NEXT_PRIVATE_START_TIME) { ...@@ -10,7 +10,12 @@ if (!process.env.NEXT_PRIVATE_START_TIME) {
import '../server/lib/cpu-profile' import '../server/lib/cpu-profile'
import { saveCpuProfile } from '../server/lib/cpu-profile' import { saveCpuProfile } from '../server/lib/cpu-profile'
import { startServer } from '../server/lib/start-server' import { startServer } from '../server/lib/start-server'
import { printAndExit } from '../server/lib/utils' import {
getParsedDebugAddress,
formatDebugAddress,
printAndExit,
type DebugAddress,
} from '../server/lib/utils'
import { getProjectDir } from '../lib/get-project-dir' import { getProjectDir } from '../lib/get-project-dir'
import { import {
getReservedPortExplanation, getReservedPortExplanation,
...@@ -21,6 +26,8 @@ import * as Log from '../build/output/log' ...@@ -21,6 +26,8 @@ import * as Log from '../build/output/log'
export type NextStartOptions = { export type NextStartOptions = {
port: number port: number
hostname?: string hostname?: string
// Commander is not putting `--inspect` through the arg parser
inspect?: DebugAddress | true
keepAliveTimeout?: number keepAliveTimeout?: number
experimentalNextConfigStripTypes?: boolean experimentalNextConfigStripTypes?: boolean
experimentalCpuProf?: boolean experimentalCpuProf?: boolean
...@@ -35,6 +42,7 @@ export type NextStartOptions = { ...@@ -35,6 +42,7 @@ export type NextStartOptions = {
const nextStart = async (options: NextStartOptions, directory?: string) => { const nextStart = async (options: NextStartOptions, directory?: string) => {
const dir = getProjectDir(directory) const dir = getProjectDir(directory)
const hostname = options.hostname const hostname = options.hostname
const inspect = options.inspect
const port = options.port const port = options.port
const keepAliveTimeout = options.keepAliveTimeout const keepAliveTimeout = options.keepAliveTimeout
...@@ -42,6 +50,30 @@ const nextStart = async (options: NextStartOptions, directory?: string) => { ...@@ -42,6 +50,30 @@ const nextStart = async (options: NextStartOptions, directory?: string) => {
printAndExit(getReservedPortExplanation(port), 1) printAndExit(getReservedPortExplanation(port), 1)
} }
if (inspect) {
const inspector = await import('inspector')
const isInspecting = inspector.url() !== undefined
if (isInspecting) {
Log.warn(
`The Node.js debugger port is already open at ${process.debugPort}. Ignoring '--inspect${inspect === true ? '' : `="${formatDebugAddress(inspect)}"`}'.`
)
} else {
const inspectAddress: DebugAddress =
inspect === true ? getParsedDebugAddress(true) : inspect
// TODO: Implement --inspect-wait
const wait = false
try {
inspector.open(inspectAddress.port, inspectAddress.host, wait)
} catch (error) {
console.error(
`Failed to start the Node.js inspector with --inspect="${formatDebugAddress(inspectAddress)}":`,
error
)
return process.exit(1)
}
}
}
if (options.experimentalCpuProf) { if (options.experimentalCpuProf) {
Log.info(`CPU profiling enabled. Profile will be saved on exit (Ctrl+C).`) Log.info(`CPU profiling enabled. Profile will be saved on exit (Ctrl+C).`)
// Save CPU profile on shutdown signals, but let start-server.ts handle graceful exit // Save CPU profile on shutdown signals, but let start-server.ts handle graceful exit
......
...@@ -281,6 +281,41 @@ describe('CLI Usage', () => { ...@@ -281,6 +281,41 @@ describe('CLI Usage', () => {
`Bad port: "${reservedPort}" is reserved for npp` `Bad port: "${reservedPort}" is reserved for npp`
) )
}) })
test('--inspect', async () => {
await nextBuild(dirBasic)
const port = await findPort()
let output = ''
let errOutput = ''
const app = await runNextCommandDev(
['start', dirBasic, '--port', '' + port, '--inspect'],
undefined,
{
onStdout(msg) {
output += stripAnsi(msg)
},
onStderr(msg) {
errOutput += stripAnsi(msg)
},
}
)
try {
await retry(() => {
expect(output).toMatch(new RegExp(`http://localhost:${port}`))
})
await retry(() => {
expect(output).toMatch(/- Debugger port:\s+9229/)
})
await retry(() => {
expect(errOutput).toMatch(/Debugger listening on/)
})
expect(errOutput).not.toContain('address already in use')
} finally {
await killApp(app)
}
})
}) })
describe('telemetry', () => { describe('telemetry', () => {
......
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