Unverified Commit 37ac3974 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

stabilize browser log forward options (#88857)

parent acd5d5ed
--- ---
title: browserDebugInfoInTerminal title: browserDebugInfoInTerminal
description: Forward browser console logs and errors to your terminal during development. description: Forward browser console logs and errors to your terminal during development.
version: experimental redirect: /docs/app/api-reference/config/next-config-js/logging#browser-console-logs
--- ---
The `experimental.browserDebugInfoInTerminal` option forwards console output and runtime errors originating in the browser to the dev server terminal. This configuration option has been moved to [`logging.browserToTerminal`](/docs/app/api-reference/config/next-config-js/logging#browser-console-logs).
This option is disabled by default. When enabled it only works in development mode. ## Migration
## Usage To migrate to the new configuration, replace `experimental.browserDebugInfoInTerminal` with `logging.browserToTerminal`:
Enable forwarding: ```js filename="next.config.js"
// Before
```ts filename="next.config.ts" switcher module.exports = {
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
browserDebugInfoInTerminal: true,
},
}
export default nextConfig
```
```js filename="next.config.js" switcher
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: { experimental: {
browserDebugInfoInTerminal: true, browserDebugInfoInTerminal: true,
}, },
} }
module.exports = nextConfig // After
``` module.exports = {
logging: {
### Serialization limits browserToTerminal: true,
Deeply nested objects/arrays are truncated using **sensible defaults**. You can tweak these limits:
- **depthLimit**: (optional) Limit stringification depth for nested objects/arrays. Default: 5
- **edgeLimit**: (optional) Max number of properties or elements to include per object or array. Default: 100
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
browserDebugInfoInTerminal: {
depthLimit: 5,
edgeLimit: 100,
},
},
}
export default nextConfig
```
```js filename="next.config.js" switcher
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
browserDebugInfoInTerminal: {
depthLimit: 5,
edgeLimit: 100,
},
},
}
module.exports = nextConfig
```
### Source location
Source locations are included by default when this feature is enabled.
```tsx filename="app/page.tsx" highlight={8}
'use client'
export default function Home() {
return (
<button
type="button"
onClick={() => {
console.log('Hello World')
}}
>
Click me
</button>
)
}
```
Clicking the button prints this message to the terminal.
```bash filename="Terminal"
[browser] Hello World (app/page.tsx:8:17)
```
To suppress them, set `showSourceLocation: false`.
- **showSourceLocation**: Include source location info when available.
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
browserDebugInfoInTerminal: {
showSourceLocation: false,
},
}, },
} }
export default nextConfig
``` ```
```js filename="next.config.js" switcher The new `logging.browserToTerminal` option supports the log level values (`true`, `'warn'`, `'error'`). Note that the object configuration options (`depthLimit`, `edgeLimit`, `showSourceLocation`) are no longer available in the new configuration.
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
browserDebugInfoInTerminal: {
showSourceLocation: false,
},
},
}
module.exports = nextConfig
```
| Version | Changes | | Version | Changes |
| --------- | ---------------------------------------------------- | | --------- | ---------------------------------------------------- |
| `v15.4.0` | experimental `browserDebugInfoInTerminal` introduced | | `v15.4.0` | experimental `browserDebugInfoInTerminal` introduced |
| `v16.2.x` | Moved to stable as `logging.browserToTerminal` |
--- ---
title: logging title: logging
description: Configure how data fetches are logged to the console when running Next.js in development mode. description: Configure logging behavior in the terminal when running Next.js in development mode.
--- ---
{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} {/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
...@@ -11,8 +11,6 @@ description: Configure how data fetches are logged to the console when running N ...@@ -11,8 +11,6 @@ description: Configure how data fetches are logged to the console when running N
You can configure the logging level and whether the full URL is logged to the console when running Next.js in development mode. You can configure the logging level and whether the full URL is logged to the console when running Next.js in development mode.
Currently, `logging` only applies to data fetching using the `fetch` API. It does not yet apply to other logs inside of Next.js.
```js filename="next.config.js" ```js filename="next.config.js"
module.exports = { module.exports = {
logging: { logging: {
...@@ -60,6 +58,64 @@ module.exports = { ...@@ -60,6 +58,64 @@ module.exports = {
} }
``` ```
### Browser Console Logs
You can forward browser console logs (such as `console.log`, `console.warn`, `console.error`) to the terminal during development. This is useful for debugging client-side code without needing to check the browser's developer tools.
```js filename="next.config.js"
module.exports = {
logging: {
browserToTerminal: true,
},
}
```
#### Options
The `browserToTerminal` option accepts the following values:
| Value | Description |
| --------- | --------------------------------------------------- |
| `'warn'` | Forward only warnings and errors, by default |
| `'error'` | Forward only errors |
| `true` | Forward all console output (log, info, warn, error) |
| `false` | Disable browser log forwarding |
```js filename="next.config.js"
module.exports = {
logging: {
browserToTerminal: 'warn',
},
}
```
#### Source Location
When enabled, browser logs include source location information (file path and line number) by default. For example:
```tsx filename="app/page.tsx" highlight={8}
'use client'
export default function Home() {
return (
<button
type="button"
onClick={() => {
console.log('Hello World')
}}
>
Click me
</button>
)
}
```
Clicking the button prints this message to the terminal:
```bash filename="Terminal"
[browser] Hello World (app/page.tsx:8:17)
```
### Disabling Logging ### Disabling Logging
In addition, you can disable the development logging by setting `logging` to `false`. In addition, you can disable the development logging by setting `logging` to `false`.
......
...@@ -332,7 +332,7 @@ export function getDefineEnv({ ...@@ -332,7 +332,7 @@ export function getDefineEnv({
: {}), : {}),
'process.env.__NEXT_BROWSER_DEBUG_INFO_IN_TERMINAL': JSON.stringify( 'process.env.__NEXT_BROWSER_DEBUG_INFO_IN_TERMINAL': JSON.stringify(
config.experimental.browserDebugInfoInTerminal || false (config.logging && config.logging.browserToTerminal) || false
), ),
'process.env.__NEXT_MCP_SERVER': !!config.experimental.mcpServer, 'process.env.__NEXT_MCP_SERVER': !!config.experimental.mcpServer,
......
...@@ -626,6 +626,9 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -626,6 +626,9 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
}), }),
]) ])
.optional(), .optional(),
browserToTerminal: z
.union([z.boolean(), z.enum(['error', 'warn'])])
.optional(),
}), }),
z.literal(false), z.literal(false),
]) ])
......
...@@ -268,6 +268,15 @@ export interface LoggingConfig { ...@@ -268,6 +268,15 @@ export interface LoggingConfig {
* You can specify a pattern to match incoming requests that should not be logged. * You can specify a pattern to match incoming requests that should not be logged.
*/ */
incomingRequests?: boolean | IncomingRequestLoggingConfig incomingRequests?: boolean | IncomingRequestLoggingConfig
/**
* Forward browser console logs to terminal.
* - `false`: Disable browser log forwarding
* - `true`: Forward all browser console output to terminal
* - `'warn'`: Forward warnings and errors to terminal
* - `'error'`: Forward only errors to terminal
*/
browserToTerminal?: boolean | 'error' | 'warn'
} }
export interface ExperimentalConfig { export interface ExperimentalConfig {
...@@ -773,6 +782,8 @@ export interface ExperimentalConfig { ...@@ -773,6 +782,8 @@ export interface ExperimentalConfig {
* - `true`: Same as 'verbose' - forward all browser console output to terminal * - `true`: Same as 'verbose' - forward all browser console output to terminal
* - `false`: Disable browser log forwarding to terminal * - `false`: Disable browser log forwarding to terminal
* - Object: Enable with custom configuration * - Object: Enable with custom configuration
*
* @deprecated Use `logging.browserToTerminal` instead.
*/ */
browserDebugInfoInTerminal?: browserDebugInfoInTerminal?:
| boolean | boolean
......
...@@ -195,6 +195,16 @@ function checkDeprecations( ...@@ -195,6 +195,16 @@ function checkDeprecations(
) )
} }
} }
// browserDebugInfoInTerminal has moved to logging.browserToTerminal
if (userConfig.experimental?.browserDebugInfoInTerminal !== undefined) {
warnOptionHasBeenDeprecated(
userConfig,
'experimental.browserDebugInfoInTerminal',
`\`experimental.browserDebugInfoInTerminal\` has been moved to \`logging.browserToTerminal\`. Please update your ${configFileName} file accordingly.`,
silent
)
}
} }
export function warnOptionHasBeenMovedOutOfExperimental( export function warnOptionHasBeenMovedOutOfExperimental(
...@@ -374,6 +384,27 @@ function assignDefaultsAndValidate( ...@@ -374,6 +384,27 @@ function assignDefaultsAndValidate(
result.experimental.trustHostHeader = true result.experimental.trustHostHeader = true
} }
// Normalize experimental.browserDebugInfoInTerminal to logging.browserToTerminal
if (
result.logging !== false &&
result.experimental?.browserDebugInfoInTerminal !== undefined
) {
const loggingConfig = result.logging || {}
if (!('browserToTerminal' in loggingConfig)) {
const expConfig = result.experimental.browserDebugInfoInTerminal
// Convert object config to simple format (level or true)
const normalizedValue =
typeof expConfig === 'object' && expConfig !== null
? (expConfig.level ?? true)
: expConfig
result.logging = {
...loggingConfig,
browserToTerminal: normalizedValue,
}
}
}
if ( if (
result.experimental?.allowDevelopmentBuild && result.experimental?.allowDevelopmentBuild &&
process.env.NODE_ENV !== 'development' process.env.NODE_ENV !== 'development'
......
...@@ -447,10 +447,7 @@ async function handleDefaultConsole( ...@@ -447,10 +447,7 @@ async function handleDefaultConsole(
type LogLevel = 'error' | 'warn' | 'verbose' type LogLevel = 'error' | 'warn' | 'verbose'
type BrowserLogConfig = type BrowserLogConfig = boolean | 'error' | 'warn'
| boolean
| LogLevel
| { level?: LogLevel; showSourceLocation?: boolean }
// Log levels from most severe to least severe // Log levels from most severe to least severe
// Lower index = more severe // Lower index = more severe
...@@ -487,14 +484,7 @@ function shouldShowEntry( ...@@ -487,14 +484,7 @@ function shouldShowEntry(
} }
// Determine the effective minimum log level // Determine the effective minimum log level
const minLevel: LogLevel = const minLevel: LogLevel = typeof config === 'string' ? config : 'verbose' // true means show everything
typeof config === 'string'
? config
: config === true
? 'verbose' // true means show everything
: typeof config === 'object'
? (config.level ?? 'verbose') // object config defaults to verbose for backward compatibility
: 'warn' // default for new installations
const minPriority = LOG_LEVEL_PRIORITY[minLevel] const minPriority = LOG_LEVEL_PRIORITY[minLevel]
......
...@@ -261,16 +261,8 @@ export const withLocation = async ( ...@@ -261,16 +261,8 @@ export const withLocation = async (
}, },
ctx: MappingContext, ctx: MappingContext,
distDir: string, distDir: string,
config: _config: boolean | 'error' | 'warn'
| boolean
| 'error'
| 'warn'
| 'verbose'
| { level?: 'error' | 'warn' | 'verbose'; showSourceLocation?: boolean }
) => { ) => {
if (typeof config === 'object' && config.showSourceLocation === false) {
return original
}
if (!stack) { if (!stack) {
return original return original
} }
......
...@@ -1008,7 +1008,9 @@ export async function createHotReloaderTurbopack( ...@@ -1008,7 +1008,9 @@ export async function createHotReloaderTurbopack(
// TODO // TODO
break break
case 'browser-logs': { case 'browser-logs': {
if (nextConfig.experimental.browserDebugInfoInTerminal) { const browserToTerminalConfig =
nextConfig.logging && nextConfig.logging.browserToTerminal
if (browserToTerminalConfig) {
await receiveBrowserLogsTurbopack({ await receiveBrowserLogsTurbopack({
entries: parsedData.entries, entries: parsedData.entries,
router: parsedData.router, router: parsedData.router,
...@@ -1016,7 +1018,7 @@ export async function createHotReloaderTurbopack( ...@@ -1016,7 +1018,7 @@ export async function createHotReloaderTurbopack(
project, project,
projectPath, projectPath,
distDir, distDir,
config: nextConfig.experimental.browserDebugInfoInTerminal, config: browserToTerminalConfig,
}) })
} }
break break
......
...@@ -603,7 +603,9 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -603,7 +603,9 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
break break
} }
case 'browser-logs': { case 'browser-logs': {
if (this.config.experimental.browserDebugInfoInTerminal) { const browserToTerminalConfig =
this.config.logging && this.config.logging.browserToTerminal
if (browserToTerminalConfig) {
await receiveBrowserLogsWebpack({ await receiveBrowserLogsWebpack({
entries: payload.entries, entries: payload.entries,
router: payload.router, router: payload.router,
...@@ -613,7 +615,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -613,7 +615,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
edgeServerStats: () => this.edgeServerStats, edgeServerStats: () => this.edgeServerStats,
rootDirectory: this.dir, rootDirectory: this.dir,
distDir: this.distDir, distDir: this.distDir,
config: this.config.experimental.browserDebugInfoInTerminal, config: browserToTerminalConfig,
}) })
} }
break break
......
...@@ -53,13 +53,9 @@ describe(`Terminal Logging (${bundlerName})`, () => { ...@@ -53,13 +53,9 @@ describe(`Terminal Logging (${bundlerName})`, () => {
next = await createNext({ next = await createNext({
files: { files: {
pages: new FileRef(join(__dirname, 'fixtures/pages')), pages: new FileRef(join(__dirname, 'fixtures/pages')),
'next.config.js': ` 'next.config.js': new FileRef(
module.exports = { join(__dirname, 'fixtures/next.config.js')
experimental: { ),
browserDebugInfoInTerminal: true
}
}
`,
}, },
}) })
}) })
...@@ -162,13 +158,9 @@ describe(`Terminal Logging (${bundlerName})`, () => { ...@@ -162,13 +158,9 @@ describe(`Terminal Logging (${bundlerName})`, () => {
next = await createNext({ next = await createNext({
files: { files: {
app: new FileRef(join(__dirname, 'fixtures/app')), app: new FileRef(join(__dirname, 'fixtures/app')),
'next.config.js': ` 'next.config.js': new FileRef(
module.exports = { join(__dirname, 'fixtures/next.config.js')
experimental: { ),
browserDebugInfoInTerminal: true
}
}
`,
}, },
}) })
}) })
...@@ -226,13 +218,9 @@ describe(`Terminal Logging (${bundlerName})`, () => { ...@@ -226,13 +218,9 @@ describe(`Terminal Logging (${bundlerName})`, () => {
next = await createNext({ next = await createNext({
files: { files: {
app: new FileRef(join(__dirname, 'fixtures/app')), app: new FileRef(join(__dirname, 'fixtures/app')),
'next.config.js': ` 'next.config.js': new FileRef(
module.exports = { join(__dirname, 'fixtures/next.config.js')
experimental: { ),
browserDebugInfoInTerminal: true
}
}
`,
}, },
}) })
}) })
...@@ -292,13 +280,9 @@ describe(`Terminal Logging (${bundlerName})`, () => { ...@@ -292,13 +280,9 @@ describe(`Terminal Logging (${bundlerName})`, () => {
next = await createNext({ next = await createNext({
files: { files: {
app: new FileRef(join(__dirname, 'fixtures/app')), app: new FileRef(join(__dirname, 'fixtures/app')),
'next.config.js': ` 'next.config.js': new FileRef(
module.exports = { join(__dirname, 'fixtures/next.config.js')
experimental: { ),
browserDebugInfoInTerminal: true
}
}
`,
}, },
}) })
}) })
...@@ -326,62 +310,4 @@ describe(`Terminal Logging (${bundlerName})`, () => { ...@@ -326,62 +310,4 @@ describe(`Terminal Logging (${bundlerName})`, () => {
await browser.close() await browser.close()
}) })
}) })
describe('Configuration Options', () => {
describe('showSourceLocation disabled', () => {
let next: NextInstance
let logs: string[] = []
let logCapture: ReturnType<typeof setupLogCapture>
let browser = null
beforeAll(async () => {
logCapture = setupLogCapture()
logs = logCapture.logs
next = await createNext({
files: {
pages: new FileRef(join(__dirname, 'fixtures/pages')),
'next.config.js': `
module.exports = {
experimental: {
browserDebugInfoInTerminal: {
showSourceLocation: false
}
}
}
`,
},
})
})
afterAll(async () => {
logCapture.restore()
await next.destroy()
})
beforeEach(() => {
logCapture.clearLogs()
})
afterEach(async () => {
if (browser) {
await browser.close()
browser = null
}
})
it('should omit source location when disabled', async () => {
browser = await webdriver(next.url, '/basic-logs')
await browser.waitForElementByCss('#log-button')
await browser.elementByCss('#log-button').click()
await retry(() => {
const logOutput = logs.join('')
expect(logOutput).toContain('[browser] Hello from browser')
expect(logOutput).not.toMatch(/\([^)]+basic-logs\.[jt]sx?:\d+:\d+\)/)
})
})
})
})
}) })
module.exports = {
logging: {
browserToTerminal: 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