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

Allow inspecting dev server on default port with `next dev --inspect` (#85037)

Co-authored-by: 's avatargraphite-app[bot] <96075541+graphite-app[bot]@users.noreply.github.com>
parent eee419ea
......@@ -22,7 +22,7 @@ Create a file named `.vscode/launch.json` at the root of your project with the f
"name": "Next.js: debug server-side",
"type": "node-terminal",
"request": "launch",
"command": "npm run dev"
"command": "npm run dev -- --inspect"
},
{
"name": "Next.js: debug client-side",
......@@ -111,23 +111,15 @@ For React-specific debugging, install the [React Developer Tools](https://react.
### Server-side code
To debug server-side Next.js code with browser DevTools, you need to pass the [`--inspect`](https://nodejs.org/api/cli.html#cli_inspect_host_port) flag to the underlying Node.js process:
To debug server-side Next.js code with browser DevTools, you need to pass the `--inspect` flag:
```bash filename="Terminal"
NODE_OPTIONS='--inspect' next dev
next dev --inspect
```
> **Good to know**: Use `NODE_OPTIONS='--inspect=0.0.0.0'` to allow remote debugging access outside localhost, such as when running the app in a Docker container.
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).
If you're using `npm run dev` or `yarn dev` then you should update the `dev` script on your `package.json`:
```json filename="package.json"
{
"scripts": {
"dev": "NODE_OPTIONS='--inspect' next dev"
}
}
```
> **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:
......@@ -140,22 +132,22 @@ ready - started server on 0.0.0.0:3000, url: http://localhost:3000
For Chrome:
1. Open a new tab and visit `chrome://inspect`
2. Click **Configure...** to ensure both debugging ports are listed
3. Add both `localhost:9229` and `localhost:9230` if they're not already present
4. Look for your Next.js application in the **Remote Target** section
5. Click **inspect** to open a separate DevTools window
6. Go to the **Sources** tab
1. Look for your Next.js application in the **Remote Target** section
1. Click **inspect** to open a separate DevTools window
1. Go to the **Sources** tab
For Firefox:
1. Open a new tab and visit `about:debugging`
2. Click **This Firefox** in the left sidebar
3. Under **Remote Targets**, find your Next.js application
4. Click **Inspect** to open the debugger
5. Go to the **Debugger** tab
1. Click **This Firefox** in the left sidebar
1. Under **Remote Targets**, find your Next.js application
1. Click **Inspect** to open the debugger
1. Go to the **Debugger** tab
Debugging server-side code works similarly to client-side debugging. When searching for files (`Ctrl+P`/`⌘+P`), your source files will have paths starting with `webpack://{application-name}/./` (where `{application-name}` will be replaced with the name of your application according to your `package.json` file).
To use `--inspect-brk` or `--inspect-wait`, you have to specify `NODE_OPTIONS` instead. e.g. `NODE_OPTIONS=--inspect-brk next dev`.
### Inspect Server Errors with Browser DevTools
When you encounter an error, inspecting the source code can help trace the root cause of errors.
......@@ -164,19 +156,7 @@ Next.js will display a Node.js icon underneath the Next.js version indicator on
### Debugging on Windows
Windows users may run into an issue when using `NODE_OPTIONS='--inspect'` as that syntax is not supported on Windows platforms. To get around this, install the [`cross-env`](https://www.npmjs.com/package/cross-env) package as a development dependency (`-D` with `npm` and `yarn`) and replace the `dev` script with the following.
```json filename="package.json"
{
"scripts": {
"dev": "cross-env NODE_OPTIONS='--inspect' next dev"
}
}
```
`cross-env` will set the `NODE_OPTIONS` environment variable regardless of which platform you are on (including Mac, Linux, and Windows) and allow you to debug consistently across devices and operating systems.
> **Good to know**: Ensure Windows Defender is disabled on your machine. This external service will check _every file read_, which has been reported to greatly increase Fast Refresh time with `next dev`. This is a known issue, not related to Next.js, but it does affect Next.js development.
Ensure Windows Defender is disabled on your machine. This external service will check _every file read_, which has been reported to greatly increase Fast Refresh time with `next dev`. This is a known issue, not related to Next.js, but it does affect Next.js development.
## More information
......
......@@ -2,14 +2,23 @@
import '../server/require-hook'
import { Argument, Command, Option } from 'next/dist/compiled/commander'
import {
Argument,
Command,
InvalidArgumentError,
Option,
} from 'next/dist/compiled/commander'
import { warn } from '../build/output/log'
import semver from 'next/dist/compiled/semver'
import { bold, cyan, italic } from '../lib/picocolors'
import { formatCliHelpOutput } from '../lib/format-cli-help-output'
import { NON_STANDARD_NODE_ENV } from '../lib/constants'
import { parseValidPositiveInteger } from '../server/lib/utils'
import {
getParsedDebugAddress,
parseValidPositiveInteger,
type DebugAddress,
} from '../server/lib/utils'
import {
SUPPORTED_TEST_RUNNERS_LIST,
type NextTestOptions,
......@@ -57,8 +66,6 @@ class NextRootCommand extends Command {
createCommand(name: string) {
const command = new Command(name)
command.addOption(new Option('--inspect').hideHelp())
command.hook('preAction', (event) => {
const commandName = event.name()
const defaultEnv = commandName === 'dev' ? 'development' : 'production'
......@@ -81,7 +88,7 @@ class NextRootCommand extends Command {
;(process.env as any).NODE_ENV = process.env.NODE_ENV || defaultEnv
;(process.env as any).NEXT_RUNTIME = 'nodejs'
if (event.getOptionValue('inspect') === true) {
if (commandName !== 'dev' && event.getOptionValue('inspect') === true) {
console.error(
`\`--inspect\` flag is deprecated. Use env variable NODE_OPTIONS instead: NODE_OPTIONS='--inspect' next ${commandName}`
)
......@@ -93,6 +100,22 @@ class NextRootCommand extends Command {
}
}
function parseValidInspectAddress(value: string): DebugAddress {
const address = getParsedDebugAddress(value)
if (Number.isNaN(address.port)) {
throw new InvalidArgumentError(
'The given value is not a valid inspect address. ' +
'Did you mean to pass an app path?\n' +
`Try switching the order of the arguments or set the default address explicitly e.g.\n` +
`next dev ${value} --inspect\n` +
`next dev --inspect= ${value}`
)
}
return address
}
const program = new NextRootCommand()
program
......@@ -162,6 +185,7 @@ program
if (options.experimentalNextConfigStripTypes) {
process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED = 'true'
}
// ensure process exits after build completes so open handles/connections
// don't cause process to hang
return import('../cli/next-build.js').then((mod) =>
......@@ -181,6 +205,12 @@ program
'If no directory is provided, the current directory will be used.'
)}`
)
.addOption(
new Option(
'--inspect [[host:]port]',
'Allows inspecting server-side code. See https://nextjs.org/docs/app/guides/debugging#server-side-code'
).argParser(parseValidInspectAddress)
)
.option('--turbo', 'Starts development mode using Turbopack.')
.option('--turbopack', 'Starts development mode using Turbopack.')
.option('--webpack', 'Starts development mode using webpack.')
......
......@@ -7,10 +7,11 @@ import {
getNodeDebugType,
getParsedDebugAddress,
getMaxOldSpaceSize,
getParsedNodeOptionsWithoutInspect,
printAndExit,
formatNodeOptions,
formatDebugAddress,
getParsedNodeOptions,
type DebugAddress,
} from '../server/lib/utils'
import * as Log from '../build/output/log'
import { getProjectDir } from '../lib/get-project-dir'
......@@ -46,6 +47,8 @@ import {
export type NextDevOptions = {
disableSourceMaps: boolean
// Commander is not putting `--inspect` through the arg parser
inspect?: DebugAddress | true
turbo?: boolean
turbopack?: boolean
webpack?: boolean
......@@ -259,8 +262,7 @@ const nextDev = async (
let resolved = false
const defaultEnv = (initialEnv || process.env) as typeof process.env
const nodeOptions = getParsedNodeOptionsWithoutInspect()
const nodeDebugType = getNodeDebugType()
const nodeOptions = getParsedNodeOptions()
let maxOldSpaceSize: string | number | undefined = getMaxOldSpaceSize()
if (!maxOldSpaceSize && !process.env.NEXT_DISABLE_MEM_OVERRIDE) {
......@@ -280,10 +282,22 @@ const nextDev = async (
nodeOptions['enable-source-maps'] = true
}
if (nodeDebugType) {
const address = getParsedDebugAddress()
const nodeDebugType = getNodeDebugType(nodeOptions)
const originalAddress =
nodeDebugType === undefined ? undefined : nodeOptions[nodeDebugType]
delete nodeOptions.inspect
delete nodeOptions['inspect-brk']
delete nodeOptions['inspect_brk']
if (nodeDebugType !== undefined) {
const address = getParsedDebugAddress(originalAddress)
address.port = address.port === 0 ? 0 : address.port + 1
nodeOptions[nodeDebugType] = formatDebugAddress(address)
} else if (options.inspect) {
const address: DebugAddress =
options.inspect === true
? getParsedDebugAddress(true)
: options.inspect
nodeOptions.inspect = formatDebugAddress(address)
}
child = fork(startServerPath, {
......
......@@ -6,7 +6,8 @@ import {
formatNodeOptions,
getNodeDebugType,
getParsedDebugAddress,
getParsedNodeOptionsWithoutInspect,
getParsedNodeOptions,
type DebugAddress,
} from '../server/lib/utils'
type FarmOptions = NonNullable<ConstructorParameters<typeof JestWorker>[1]>
......@@ -78,19 +79,25 @@ export class Worker {
this.close()
})
const nodeOptions = getParsedNodeOptionsWithoutInspect()
const nodeOptions = getParsedNodeOptions()
const originalOptions = { ...nodeOptions }
delete nodeOptions.inspect
delete nodeOptions['inspect-brk']
delete nodeOptions['inspect_brk']
if (debuggerPortOffset !== -1) {
const nodeDebugType = getNodeDebugType()
const nodeDebugType = getNodeDebugType(originalOptions)
if (nodeDebugType) {
const address = getParsedDebugAddress()
address.port =
address.port === 0
? 0
: address.port +
// current process runs on `address.port`
1 +
debuggerPortOffset
const debuggerAddress = getParsedDebugAddress(
originalOptions[nodeDebugType]
)
const address: DebugAddress = {
host: debuggerAddress.host,
// current process runs on `address.port`
port:
debuggerAddress.port === 0
? 0
: debuggerAddress.port + 1 + debuggerPortOffset,
}
nodeOptions[nodeDebugType] = formatDebugAddress(address)
}
}
......
......@@ -78,7 +78,7 @@ import { generateEncryptionKeyBase64 } from '../app-render/encryption-utils-serv
import { isAppPageRouteDefinition } from '../route-definitions/app-page-route-definition'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import type { ModernSourceMapPayload } from '../lib/source-maps'
import { getNodeDebugType } from '../lib/utils'
import { getNodeDebugType, getParsedNodeOptions } from '../lib/utils'
import { isMetadataRouteFile } from '../../lib/metadata/is-metadata-route'
import { setBundlerFindSourceMapImplementation } from '../patch-error-inspect'
import { getNextErrorFeedbackMiddleware } from '../../next-devtools/server/get-next-error-feedback-middleware'
......@@ -810,7 +810,8 @@ export async function createHotReloaderTurbopack(
}
let devtoolsFrontendUrl: string | undefined
const nodeDebugType = getNodeDebugType()
const nodeOptions = getParsedNodeOptions()
const nodeDebugType = getNodeDebugType(nodeOptions)
if (nodeDebugType) {
const debugPort = process.debugPort
let debugInfo
......
......@@ -81,7 +81,7 @@ import type { HmrMessageSentToBrowser } from './hot-reloader-types'
import type { WebpackError } from 'webpack'
import { PAGE_TYPES } from '../../lib/page-types'
import { FAST_REFRESH_RUNTIME_RELOAD } from './messages'
import { getNodeDebugType } from '../lib/utils'
import { getNodeDebugType, getParsedNodeOptions } from '../lib/utils'
import { getNextErrorFeedbackMiddleware } from '../../next-devtools/server/get-next-error-feedback-middleware'
import { getDevOverlayFontMiddleware } from '../../next-devtools/server/font/get-dev-overlay-font-middleware'
import { getDisableDevIndicatorMiddleware } from '../../next-devtools/server/dev-indicator-middleware'
......@@ -860,7 +860,8 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
this.versionInfo = await this.tracedGetVersionInfo(startSpan)
const nodeDebugType = getNodeDebugType()
const nodeOptions = getParsedNodeOptions()
const nodeDebugType = getNodeDebugType(nodeOptions)
if (nodeDebugType && !this.devtoolsFrontendUrl) {
const debugPort = process.debugPort
let debugInfo
......
import { loadEnvConfig } from '@next/env'
import * as inspector from 'inspector'
import * as Log from '../../build/output/log'
import { bold, purple, strikethrough } from '../../lib/picocolors'
import {
......@@ -50,10 +51,19 @@ export function logStartInfo({
)}${versionSuffix}`
)
if (appUrl) {
Log.bootstrap(`- Local: ${appUrl}`)
Log.bootstrap(`- Local: ${appUrl}`)
}
if (networkUrl) {
Log.bootstrap(`- Network: ${networkUrl}`)
Log.bootstrap(`- Network: ${networkUrl}`)
}
const inspectorUrl = inspector.url()
if (inspectorUrl) {
// Could also parse this port from the inspector URL.
// process.debugPort will always be defined even if the process is not being inspected.
// The full URL seems noisy as far as I can tell.
// Node.js will print the full URL anyway.
const debugPort = process.debugPort
Log.bootstrap(`- Debugger port: ${debugPort}`)
}
if (envInfo?.length) Log.bootstrap(`- Environments: ${envInfo.join(', ')}`)
......
......@@ -22,12 +22,7 @@ import { exec } from 'child_process'
import Watchpack from 'next/dist/compiled/watchpack'
import * as Log from '../../build/output/log'
import setupDebug from 'next/dist/compiled/debug'
import {
RESTART_EXIT_CODE,
getFormattedDebugAddress,
getNodeDebugType,
isDebugAddressEphemeral,
} from './utils'
import { RESTART_EXIT_CODE } from './utils'
import { formatHostname } from './format-hostname'
import { initialize } from './router-server'
import { CONFIG_FILES } from '../../shared/lib/constants'
......@@ -305,8 +300,6 @@ export async function startServer(
await new Promise<void>((resolve) => {
server.on('listening', async () => {
const nodeDebugType = getNodeDebugType()
const addr = server.address()
const actualHostname = formatHostname(
typeof addr === 'object'
......@@ -346,17 +339,6 @@ export async function startServer(
const appUrl = `${protocol}://${formattedHostname}:${port}`
if (nodeDebugType) {
const formattedDebugAddress = getFormattedDebugAddress()
const isEphemeral = isDebugAddressEphemeral()
Log.info(
`the --${nodeDebugType} option was detected` +
(isEphemeral
? ''
: `, the Next.js router server should be inspected at ${formattedDebugAddress}.`)
)
}
// Store the selected port to:
// - expose it to render workers
// - re-use it for automatic dev server restarts with a randomly selected port
......
......@@ -3,6 +3,7 @@ import {
getParsedDebugAddress,
formatNodeOptions,
tokenizeArgs,
getParsedNodeOptions,
} from './utils'
const originalNodeOptions = process.env.NODE_OPTIONS
......@@ -56,13 +57,15 @@ describe('formatNodeOptions', () => {
describe('getParsedDebugAddress', () => {
it('supports the flag with an equal sign', () => {
process.env.NODE_OPTIONS = '--inspect=1234'
const result = getParsedDebugAddress()
const nodeOptions = getParsedNodeOptions()
const result = getParsedDebugAddress(nodeOptions.inspect)
expect(result).toEqual({ host: undefined, port: 1234 })
})
it('supports the flag without an equal sign', () => {
process.env.NODE_OPTIONS = '--inspect 1234'
const result = getParsedDebugAddress()
const nodeOptions = getParsedNodeOptions()
const result = getParsedDebugAddress(nodeOptions.inspect)
expect(result).toEqual({ host: undefined, port: 1234 })
})
})
......
......@@ -11,7 +11,9 @@ export function printAndExit(message: string, code = 1) {
return process.exit(code)
}
const parseNodeArgs = (args: string[]) => {
export type NodeOptions = Record<string, string | boolean | undefined>
const parseNodeArgs = (args: string[]): NodeOptions => {
const { values, tokens } = parseArgs({ args, strict: false, tokens: true })
// For the `NODE_OPTIONS`, we support arguments with values without the `=`
......@@ -127,7 +129,7 @@ export const getNodeOptionsArgs = () => {
/**
* The debug address is in the form of `[host:]port`. The host is optional.
*/
type DebugAddress = {
export interface DebugAddress {
host: string | undefined
port: number
}
......@@ -147,17 +149,9 @@ export const formatDebugAddress = ({ host, port }: DebugAddress): string => {
*
* @returns An object with the host and port of the debug address.
*/
export const getParsedDebugAddress = (): DebugAddress => {
const args = getNodeOptionsArgs()
if (args.length === 0) return { host: undefined, port: 9229 }
const parsed = parseNodeArgs(args)
// We expect to find the debug port in one of these options. The first one
// found will be used.
const address =
parsed.inspect ?? parsed['inspect-brk'] ?? parsed['inspect_brk']
export const getParsedDebugAddress = (
address: string | boolean | undefined
): DebugAddress => {
if (!address || typeof address !== 'string') {
return { host: undefined, port: 9229 }
}
......@@ -171,22 +165,6 @@ export const getParsedDebugAddress = (): DebugAddress => {
return { host: undefined, port: parseInt(address, 10) }
}
/**
* Checks if the debug address from `NODE_OPTIONS` specifies to use a random port (e.g., the port set to 0).
*
* @returns A boolean indicating whether or not the debug address is assigned to a random port.
*/
export const isDebugAddressEphemeral = () => getParsedDebugAddress()?.port === 0
/**
* Get the debug address from the `NODE_OPTIONS` environment variable and format
* it into a string.
*
* @returns A string with the formatted debug address.
*/
export const getFormattedDebugAddress = () =>
formatDebugAddress(getParsedDebugAddress())
/**
* Stringify the arguments to be used in a command line. It will ignore any
* argument that has a value of `undefined`.
......@@ -219,6 +197,16 @@ export function formatNodeOptions(
.join(' ')
}
export function getParsedNodeOptions(): Record<
string,
string | boolean | undefined
> {
const args = [...process.execArgv, ...getNodeOptionsArgs()]
if (args.length === 0) return {}
return parseNodeArgs(args)
}
/**
* Get the node options from the `NODE_OPTIONS` environment variable and parse
* them into an object without the inspect options.
......@@ -273,14 +261,13 @@ export type NodeInspectType = 'inspect' | 'inspect-brk' | undefined
/**
* Get the debug type from the `NODE_OPTIONS` environment variable.
*/
export function getNodeDebugType(): NodeInspectType {
const args = [...process.execArgv, ...getNodeOptionsArgs()]
if (args.length === 0) return
const parsed = parseNodeArgs(args)
if (parsed.inspect) return 'inspect'
if (parsed['inspect-brk'] || parsed['inspect_brk']) return 'inspect-brk'
export function getNodeDebugType(nodeOptions: NodeOptions): NodeInspectType {
if (nodeOptions.inspect) {
return 'inspect'
}
if (nodeOptions['inspect-brk'] || nodeOptions['inspect_brk']) {
return 'inspect-brk'
}
}
/**
......
......@@ -561,11 +561,87 @@ describe('CLI Usage', () => {
)
try {
await check(() => output, new RegExp(`http://localhost:${port}`))
await check(() => output, /- Debugger port:\s+\d+/)
await check(() => errOutput, /Debugger listening on/)
expect(errOutput).not.toContain('address already in use')
} finally {
await killApp(app)
}
})
test('--inspect', async () => {
const port = await findPort()
let output = ''
let errOutput = ''
const app = await runNextCommandDev(
[dirBasic, '--port', port, '--inspect'],
undefined,
{
onStdout(msg) {
output += stripAnsi(msg)
},
onStderr(msg) {
errOutput += stripAnsi(msg)
},
}
)
try {
await check(() => output, new RegExp(`http://localhost:${port}`))
await check(() => output, /- Debugger port:\s+9229/)
await check(() => errOutput, /Debugger listening on/)
expect(errOutput).not.toContain('address already in use')
} finally {
await killApp(app)
}
})
test('--inspect 0', async () => {
const port = await findPort()
let output = ''
let errOutput = ''
const app = await runNextCommandDev(
[dirBasic, '--port', port, '--inspect', '0'],
undefined,
{
onStdout(msg) {
output += stripAnsi(msg)
},
onStderr(msg) {
errOutput += stripAnsi(msg)
},
}
)
try {
await check(() => output, new RegExp(`http://localhost:${port}`))
await check(() => output, /- Debugger port:\s+\d+/)
await check(() => errOutput, /Debugger listening on/)
expect(errOutput).not.toContain('address already in use')
} finally {
await killApp(app)
}
})
test('--inspect [port]', async () => {
const port = await findPort()
let output = ''
let errOutput = ''
const app = await runNextCommandDev(
[dirBasic, '--port', port, '--inspect', '9230'],
undefined,
{
onStdout(msg) {
output += stripAnsi(msg)
},
onStderr(msg) {
errOutput += stripAnsi(msg)
},
}
)
try {
await check(() => output, new RegExp(`http://localhost:${port}`))
await check(() => output, /- Debugger port:\s+9230/)
await check(() => errOutput, /Debugger listening on/)
expect(errOutput).not.toContain('address already in use')
expect(output).toContain(
'the --inspect option was detected, the Next.js router server should be inspected at'
)
} finally {
await killApp(app)
}
......@@ -590,11 +666,11 @@ describe('CLI Usage', () => {
)
try {
await check(() => output, new RegExp(`http://localhost:${port}`))
await check(() => output, /- Debugger port:\s+\d+/)
await check(() => errOutput, /Debugger listening on/)
expect(errOutput).not.toContain('address already in use')
expect(errOutput).toContain('Debugger listening on')
console.log(output)
expect(output).toContain('the --inspect option was detected')
} finally {
await killApp(app)
}
......
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