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

stabilize browser log forward options (#88857)

parent acd5d5ed
---
title: browserDebugInfoInTerminal
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:
```ts filename="next.config.ts" switcher
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 = {
```js filename="next.config.js"
// Before
module.exports = {
experimental: {
browserDebugInfoInTerminal: true,
},
}
module.exports = nextConfig
```
### Serialization limits
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,
},
// After
module.exports = {
logging: {
browserToTerminal: true,
},
}
export default nextConfig
```
```js filename="next.config.js" switcher
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
browserDebugInfoInTerminal: {
showSourceLocation: false,
},
},
}
module.exports = nextConfig
```
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.
| Version | Changes |
| --------- | ---------------------------------------------------- |
| `v15.4.0` | experimental `browserDebugInfoInTerminal` introduced |
| `v16.2.x` | Moved to stable as `logging.browserToTerminal` |
---
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. */}
......@@ -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.
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"
module.exports = {
logging: {
......@@ -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
In addition, you can disable the development logging by setting `logging` to `false`.
......
......@@ -332,7 +332,7 @@ export function getDefineEnv({
: {}),
'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,
......
......@@ -626,6 +626,9 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
}),
])
.optional(),
browserToTerminal: z
.union([z.boolean(), z.enum(['error', 'warn'])])
.optional(),
}),
z.literal(false),
])
......
......@@ -268,6 +268,15 @@ export interface LoggingConfig {
* You can specify a pattern to match incoming requests that should not be logged.
*/
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 {
......@@ -773,6 +782,8 @@ export interface ExperimentalConfig {
* - `true`: Same as 'verbose' - forward all browser console output to terminal
* - `false`: Disable browser log forwarding to terminal
* - Object: Enable with custom configuration
*
* @deprecated Use `logging.browserToTerminal` instead.
*/
browserDebugInfoInTerminal?:
| boolean
......
......@@ -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(
......@@ -374,6 +384,27 @@ function assignDefaultsAndValidate(
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 (
result.experimental?.allowDevelopmentBuild &&
process.env.NODE_ENV !== 'development'
......
......@@ -447,10 +447,7 @@ async function handleDefaultConsole(
type LogLevel = 'error' | 'warn' | 'verbose'
type BrowserLogConfig =
| boolean
| LogLevel
| { level?: LogLevel; showSourceLocation?: boolean }
type BrowserLogConfig = boolean | 'error' | 'warn'
// Log levels from most severe to least severe
// Lower index = more severe
......@@ -487,14 +484,7 @@ function shouldShowEntry(
}
// Determine the effective minimum log level
const minLevel: LogLevel =
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 minLevel: LogLevel = typeof config === 'string' ? config : 'verbose' // true means show everything
const minPriority = LOG_LEVEL_PRIORITY[minLevel]
......
......@@ -261,16 +261,8 @@ export const withLocation = async (
},
ctx: MappingContext,
distDir: string,
config:
| boolean
| 'error'
| 'warn'
| 'verbose'
| { level?: 'error' | 'warn' | 'verbose'; showSourceLocation?: boolean }
_config: boolean | 'error' | 'warn'
) => {
if (typeof config === 'object' && config.showSourceLocation === false) {
return original
}
if (!stack) {
return original
}
......
......@@ -1008,7 +1008,9 @@ export async function createHotReloaderTurbopack(
// TODO
break
case 'browser-logs': {
if (nextConfig.experimental.browserDebugInfoInTerminal) {
const browserToTerminalConfig =
nextConfig.logging && nextConfig.logging.browserToTerminal
if (browserToTerminalConfig) {
await receiveBrowserLogsTurbopack({
entries: parsedData.entries,
router: parsedData.router,
......@@ -1016,7 +1018,7 @@ export async function createHotReloaderTurbopack(
project,
projectPath,
distDir,
config: nextConfig.experimental.browserDebugInfoInTerminal,
config: browserToTerminalConfig,
})
}
break
......
......@@ -603,7 +603,9 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
break
}
case 'browser-logs': {
if (this.config.experimental.browserDebugInfoInTerminal) {
const browserToTerminalConfig =
this.config.logging && this.config.logging.browserToTerminal
if (browserToTerminalConfig) {
await receiveBrowserLogsWebpack({
entries: payload.entries,
router: payload.router,
......@@ -613,7 +615,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
edgeServerStats: () => this.edgeServerStats,
rootDirectory: this.dir,
distDir: this.distDir,
config: this.config.experimental.browserDebugInfoInTerminal,
config: browserToTerminalConfig,
})
}
break
......
......@@ -53,13 +53,9 @@ describe(`Terminal Logging (${bundlerName})`, () => {
next = await createNext({
files: {
pages: new FileRef(join(__dirname, 'fixtures/pages')),
'next.config.js': `
module.exports = {
experimental: {
browserDebugInfoInTerminal: true
}
}
`,
'next.config.js': new FileRef(
join(__dirname, 'fixtures/next.config.js')
),
},
})
})
......@@ -162,13 +158,9 @@ describe(`Terminal Logging (${bundlerName})`, () => {
next = await createNext({
files: {
app: new FileRef(join(__dirname, 'fixtures/app')),
'next.config.js': `
module.exports = {
experimental: {
browserDebugInfoInTerminal: true
}
}
`,
'next.config.js': new FileRef(
join(__dirname, 'fixtures/next.config.js')
),
},
})
})
......@@ -226,13 +218,9 @@ describe(`Terminal Logging (${bundlerName})`, () => {
next = await createNext({
files: {
app: new FileRef(join(__dirname, 'fixtures/app')),
'next.config.js': `
module.exports = {
experimental: {
browserDebugInfoInTerminal: true
}
}
`,
'next.config.js': new FileRef(
join(__dirname, 'fixtures/next.config.js')
),
},
})
})
......@@ -292,13 +280,9 @@ describe(`Terminal Logging (${bundlerName})`, () => {
next = await createNext({
files: {
app: new FileRef(join(__dirname, 'fixtures/app')),
'next.config.js': `
module.exports = {
experimental: {
browserDebugInfoInTerminal: true
}
}
`,
'next.config.js': new FileRef(
join(__dirname, 'fixtures/next.config.js')
),
},
})
})
......@@ -326,62 +310,4 @@ describe(`Terminal Logging (${bundlerName})`, () => {
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