Someone writes: "Last night I tried to book and got an error. The reference was 2847159". What would you do with that message today? The number is in the terminal of a server that has since restarted, among thousands of unordered lines, and nothing links it to the query that failed or to the other people affected. The application works; what we don't have is a way to know what it does when nobody is watching.

This lesson covers both ends. First debugging, which is understanding a failure that's right in front of you: breakpoints on the server and in the browser, and what to look at when the cache is the suspect. Then observability, which is being able to understand one that happened in production: structured logs without personal data, error capture with instrumentation.ts, traces with OpenTelemetry, health checks and alerts. Along the way, the promises made in 02-04, 07-02 and 07-04 will be kept.

  1. Debugging locally

console.log goes a long way, and Next.js improves it: in development, whatever a Server Component writes also shows up in the browser console, marked as coming from the server. When that's not enough, there are two debuggers, one per environment.

1.1. The server

npm run dev -- --inspect
# To stop before running anything
NODE_OPTIONS=--inspect-brk npm run dev

Open chrome://inspect in Chrome, find the application under Remote Target and click inspect. You can set breakpoints in a Server Component, a Server Action or proxy.ts. From VS Code it's more convenient, with this file:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Server",
      "type": "node-terminal",
      "request": "launch",
      "command": "npm run dev -- --inspect"
    },
    {
      "name": "Browser",
      "type": "chrome",
      "request": "launch",
      "url": "http://localhost:3000"
    }
  ]
}

It goes in .vscode/launch.json. Press F5 and, if you need both sides, launch both configurations.

  • The debugging port lets anyone run anything. --inspect only listens on your machine; --inspect=0.0.0.0, useful inside a local container, opens it to the network. Never in production.
  • A breakpoint stops the entire process, including other requests.
  • Remember when each thing runs. The body of a function with 'use cache' doesn't run on a hit: a breakpoint that doesn't trigger may be good news. In development, its console.log calls carry the Cache prefix.
  • Browser errors show the Node icon in the overlay: copy the address to inspect the process.

For a performance problem on the server, npx next start --experimental-cpu-prof saves a profile in .next-profiles/ on exit, which you can open in DevTools. And for a memory problem, --inspect and two heap snapshots taken a while of use apart.

1.2. Agents

The development server also exposes an MCP server at /_next/mcp, which a coding assistant can use to ask what errors there are, which routes exist, where a Server Action is or whether a route compiles. It connects with the next-devtools-mcp package. It only exists in development; if you don't want it, experimental.mcpServer: false.

1.3. Did the cache hit?

It's the most frequent question with Cache Components, and it has three answers depending on what you look at:

Question How it's answered
Did this function run or come from the cache? NEXT_PRIVATE_DEBUG_CACHE=1 npm run start: the server logs every lookup and every revalidation
Was this page served prerendered? The x-nextjs-cache response header: HIT, STALE, MISS or REVALIDATED
What's part of the shell? The Navigation Inspector (10-02) or a test with instant() (10-04)
NEXT_PRIVATE_DEBUG_CACHE=1 npm run start 2>&1 | grep -i cache
curl -sI localhost:3000/events/jazz-night | grep -i x-nextjs

The log is very detailed and its format isn't stable: it's for a diagnosis, not for leaving switched on. The variable is documented, despite its name. If an entry never hits, go over the list from 05-02: arguments that change on every call (a date, an object with an extra field), a lifetime that's too short, or several instances with separate caches.

  1. Structured logs

A useful log is read by programs before people. Error saving an event: … forces you to search by phrases; one JSON object per line lets you ask "booking errors in the last hour, by route". We'll replace our scattered console calls with a function:

npm install @opentelemetry/api
// lib/log.ts — no server-only: proxy.ts uses it too
import { trace } from '@opentelemetry/api'

type Level = 'info' | 'warn' | 'error'
export type LogData = Record<string, string | number | boolean | null | undefined>

export function log(level: Level, event: string, data: LogData = {}): void {
  const write = { info: console.info, warn: console.warn, error: console.error }[level]
  const traceId = trace.getActiveSpan()?.spanContext().traceId

  if (process.env.NODE_ENV === 'development') write(event, data)
  else write(JSON.stringify({ level, event, trace: traceId, ...data }))
}

// What can be said about an error without saying what it carried inside
export function describeError(error: unknown): LogData {
  if (!(error instanceof Error)) return { type: typeof error }

  return {
    type: error.name,
    message: error.message.split('\nparams:')[0].slice(0, 300),
    stack: error.stack?.split('\n').filter((line) => /^\s+at /.test(line)).slice(0, 8).join('\n'),
    digest: 'digest' in error && typeof error.digest === 'string' ? error.digest : undefined,
    cause: error.cause instanceof Error ? error.cause.name : undefined,
  }
}
{"level":"error","event":"exception","trace":"4bf9…","route":"/events/[slug]","kind":"render","type":"Error","digest":"2847159"}
  • event is a fixed, short name (mail.rejected, sign-in.limited), not a sentence with data inside. Whatever varies goes in fields.
  • params: is cut off. A Drizzle query error includes the SQL and the values in its message: the email address of whoever is signing up, an event's description. The stack trace starts by repeating the message, which is why only the at lines are kept.
  • There's no time. Whoever collects the output (Docker, the platform) adds it, and that way there's no new Date() getting in the way of prerendering (05-01).
  • trace links the line to the OpenTelemetry trace from section 4. Without it, it stays empty and nothing happens.
  • It's written to standard output. Storing, rotating and shipping files is the environment's job, not the application's.
  • JSON.stringify escapes line breaks: nobody can forge an entry (08-05).

For large volumes there are libraries like pino, with configurable levels and writing on another thread; Next.js already excludes it from the server bundle. With log as the only way in, switching is a matter of touching one file.

2.1. What isn't logged

Never Instead
Passwords, tokens, cookies, Authorization headers Nothing. Not even truncated
Email addresses, names, text someone wrote The user's identifier, if needed
The request body or the FormData The names of the fields with errors
The URL with parameters The route pattern
The IP Nothing, or a hash, if there's a legal basis and a deletion period
The whole object (log(…, user)) Chosen fields. The LogData type doesn't accept objects, on purpose

Logs end up in another system, often run by another company, more people read them than read the database, and they're kept for months. They're data processing like any other: set a retention period and who has access, and check it with whoever handles compliance.

2.2. The changes

Where Before Now
lib/api/responses.ts, guarded console.error('API error:', …) log('error', 'api.exception', describeError(error))
lib/tasks/after-response.ts console.error(…) captureError (section 3)
lib/proxy/events.ts console.error(…) log('warn', 'proxy.unchecked', …)
lib/mail.ts console.error(…) log('error', 'mail.rejected', { status })
lib/db/client.ts, pool.on('error') console.error(…) log('error', 'db.connection', …)
actions/events.ts, images.ts console.error(…) captureError
app/api/metrics, app/api/csp console.info, console.warn log('info', 'metric', body.data), log('warn', 'csp', …)
lib/data/weather.ts console.error(…) log('warn', 'weather.no-data', …)
Venue webhook, cleanup console.info(…) log('info', …)

Notice the levels. The forecast not arriving is a warning: it's expected and the page tolerates it. A booking failing is an error. If everything is an error, nobody looks.

  1. Errors: instrumentation.ts

Next.js catches the errors that happen during rendering, in Route Handlers, in actions and in the proxy. If instrumentation.ts exports onRequestError, it receives all of them in a single place:

// lib/observability.ts
import 'server-only'
import { readEnv } from '@/lib/env'
import { type LogData, describeError, log } from '@/lib/log'

export async function captureError(error: unknown, context: LogData): Promise<void> {
  const data = { ...context, ...describeError(error) }
  log('error', 'exception', data)

  try {
    const { errorsUrl } = readEnv() // ERRORS_URL: optional
    if (!errorsUrl) return
    await fetch(errorsUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
      signal: AbortSignal.timeout(2000),
      redirect: 'error',
    })
  } catch {
    log('warn', 'errors.unsent')
  }
}
// instrumentation.ts
import type { Instrumentation } from 'next'

export async function register() {
  if (process.env.NEXT_RUNTIME === 'nodejs') {
    const { readEnv } = await import('@/lib/env')
    readEnv()

    if (process.env.OTEL_EXPORTER_OTLP_ENDPOINT) await import('./instrumentation.node')
  }
}

export const onRequestError: Instrumentation.onRequestError = async (error, request, context) => {
  if (process.env.NEXT_RUNTIME === 'nodejs') {
    const { captureError } = await import('@/lib/observability')
    const requestId = request.headers['x-request-id']

    await captureError(error, {
      route: context.routePath,
      kind: context.routeType, // render, route, action or proxy
      source: context.renderSource,
      revalidation: context.revalidateReason, // Has a value if nobody was waiting for the response
      method: request.method,
      requestId: typeof requestId === 'string' ? requestId : null,
    })
  }
}
  • routePath and not path. The latter is the real address with its parameters; the former, the pattern.
  • The digest is the reference. In production, the browser receives an error with no details and with that hash; ErrorNotice shows it (02-04) and here it gets logged. The person from the beginning finally has something to search for: digest=2847159.
  • Async work is awaited (await), as the documentation asks, and it has its own timeout: reporting an error mustn't turn into another one.
  • The error may not be the original. When rendering Server Components, React processes it; that's why the digest and the cause are noted as well.
  • revalidateReason identifies a failure while revalidating the cache in the background. Nobody saw it, and precisely for that reason nobody will report it: the old page keeps being served until it expires.
  • What you catch yourself doesn't arrive here. A catch that responds gracefully must call captureError or log.

ERRORS_URL is the hook-up point for an error tracking service. Commercial ones, like Sentry, offer an SDK that does this and more (grouping, alerting, linking releases) and that's wired into these same files. Before installing one, check three things: what data it collects by default, how much JavaScript it adds (10-02) and which domains it needs in the CSP.

3.1. Post-response tasks

// lib/tasks/after-response.ts
export function afterResponse(name: string, task: () => Promise<unknown>): void {
  after(async () => {
    try {
      await task()
    } catch (error) {
      await captureError(error, { task: name })
    }
  })
}

It's the change we promised in 07-04, in the only place where it had to be made.

3.2. The browser

Client Component failures don't go through the server. Next.js runs instrumentation-client.ts before hydration, so whatever listens there will see even errors during start-up:

// lib/browser-errors.ts
import 'client-only'
import { routePattern } from '@/lib/metrics'

const MAX_PER_VISIT = 5
let sent = 0

export function reportFromBrowser(error: unknown, digest: string | null = null): void {
  if (sent++ >= MAX_PER_VISIT) return

  const { name, message, stack = '' } =
    error instanceof Error ? error : { name: 'Unknown', message: '', stack: '' }
  const body = JSON.stringify({
    type: name.slice(0, 60),
    message: message.slice(0, 300),
    stack: stack.slice(0, 2000),
    route: routePattern(window.location.pathname),
    digest,
  })
  navigator.sendBeacon('/api/errors', new Blob([body], { type: 'application/json' }))
}
// instrumentation-client.ts
import { reportFromBrowser } from '@/lib/browser-errors'

window.addEventListener('error', (event) => reportFromBrowser(event.error))
window.addEventListener('unhandledrejection', (event) => reportFromBrowser(event.reason))
// app/api/errors/route.ts
import * as z from 'zod'
import { readJson } from '@/lib/api/body'
import { errorResponse, guarded } from '@/lib/api/responses'
import { log } from '@/lib/log'
import { getIp } from '@/lib/security/ip'
import { withinLimits } from '@/lib/security/rate-limits'

const schema = z.strictObject({
  type: z.string().max(60),
  message: z.string().max(300),
  stack: z.string().max(2000),
  route: z.string().max(60),
  digest: z.string().max(60).nullable(),
})

export async function POST(request: Request) {
  return guarded(async () => {
    const limit = { key: `errors-ip:${await getIp()}`, max: 20, seconds: 60 }
    if (!(await withinLimits([limit]))) {
      return errorResponse('too-many-requests', 'Too many reports.')
    }
    const body = await readJson(request, schema)
    if (!body.valid) return body.response

    log('error', 'browser.exception', body.data)
    return new Response(null, { status: 204 })
  })
}

In ErrorNotice, the effect calls reportFromBrowser(error, reference) instead of console.error. With a digest, the server had already counted it and the report says that someone saw it; without one, it's an error from the browser itself.

The per-visit maximum keeps an error in a loop from sending thousands. The list will bring noise: extensions, translators, bots. Filter by the file path (/_next/static/) and look at how many distinct visits are affected, not how many lines there are. And in browser code, nothing heavy: Next.js warns in development if instrumentation-client.ts takes more than 16 ms. The file can also export onRouterTransitionStart, which is called at the start of every navigation.

3.3. Source maps

A minified stack trace (a.js:1:48213) doesn't help. Source maps give you back the file and the line, but publishing them means publishing the client's source code. That's why productionBrowserSourceMaps is disabled by default. The usual practice is to generate them at build time, upload them to the error service and delete them before deploying. Browser code is public anyway, so it isn't a secret; it's about not giving away comments and names.

  1. Traces with OpenTelemetry

A log says what happened; a trace, where the time went. It's a tree of spans with a start and an end: the request, the route render, the metadata, each fetch. Next.js already produces them; all that's missing is something to collect them. OpenTelemetry is the standard, and almost every service understands it.

There are two ways to hook it up. @vercel/otel is the one the guide presents first, with a single line; it works outside Vercel too. At the time of writing, its dependencies accept versions of the OpenTelemetry packages older than the latest ones, so check them before mixing. The other is the official SDK for Node.js, which we'll use:

npm install @opentelemetry/sdk-node
// instrumentation.node.ts
import { NodeSDK } from '@opentelemetry/sdk-node'

const sdk = new NodeSDK() // Configured through the OTEL_* variables
sdk.start()

process.once('SIGTERM', () => {
  sdk.shutdown().catch(() => {}) // Sends what's pending; Next.js ends the process
})
# A local viewer, at http://localhost:16686
docker run --rm --name jaeger -p 16686:16686 -p 4318:4318 cr.jaegertracing.io/jaegertracing/jaeger:2.23.0

# In another terminal
OTEL_SERVICE_NAME=agendaviva \
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 \
OTEL_METRICS_EXPORTER=none OTEL_LOGS_EXPORTER=none \
npm run start

Visit a few pages and look for the agendaviva service. Every request is a trace with a root like GET /events/[slug] and, inside it, render route (app), generateMetadata or the fetch calls. With NEXT_OTEL_VERBOSE=1 there's more. Look at a prefetch (next.rsc: true) and at an event page served from the shell: the render span is short, because only the holes are filled in.

  • Without the variable, nothing is loaded. register checks OTEL_EXPORTER_OTLP_ENDPOINT, so in development and in the tests the SDK doesn't exist.
  • It's imported dynamically and only in Node.js, as the documentation asks.
  • Sampling. In production, keeping one in ten is enough: OTEL_TRACES_SAMPLER=parentbased_traceidratio and OTEL_TRACES_SAMPLER_ARG=0.1.
  • Attributes are data too. http.target contains the requested address, with its parameters. If any of them may be personal, filter it in the collector, which is the intermediate program the traces are sent to (OpenTelemetry Collector).

4.1. Custom spans

Next.js doesn't know what a booking is. To measure an operation of our own:

// lib/tracing.ts
import 'server-only'
import { SpanStatusCode, trace } from '@opentelemetry/api'

export function measure<T>(name: string, operation: () => Promise<T>): Promise<T> {
  return trace.getTracer('agendaviva').startActiveSpan(name, async (span) => {
    try {
      return await operation()
    } catch (error) {
      span.setStatus({ code: SpanStatusCode.ERROR })
      throw error
    } finally {
      span.end()
    }
  })
}

// lib/data/bookings.ts, in createBooking
const db = await getDb()
return measure('bookings.create', () =>
  db.transaction(async (tx): Promise<BookingResult> => {
    // … unchanged
  }),
)

measure goes after getDb(). Opening a span reads the clock and, before an await, a component being prerendered would trigger the error from 05-01. With the SDK switched off, the @opentelemetry/api functions do nothing: the code is the same.

Automatic instrumentations (@opentelemetry/instrumentation-pg) would add a span per query without writing anything, by intercepting module loading. With a bundler in between they don't always manage it; if you try it, check that the pg.query spans appear before relying on it, and don't enable enhancedDatabaseReporting, which includes the values.

  1. Putting it all together

Data Born in Appears in
x-request-id proxy.ts (07-02) Response header, onRequestError errors, audit_log table
digest Next.js, on failure What the person sees, server and browser logs
trace OpenTelemetry Logs and trace viewer

With that, the message from the beginning is solved in three steps. The reference leads to the error line, with its route and its trace. The trace shows that the transaction waited nine seconds. And the other lines with the same type at that time tell you how many people it happened to. If there was also a write, audit_log says who, without the log having had to carry their name.

Prefetches don't go through the proxy and have no identifier; it's normal for it to be missing. Also check, in your setup, that the header the proxy added reaches onRequestError: it depends on how it's deployed.

In a Route Handler you can return the identifier to the integrator inside the error, and on error screens, show both. They're numbers with no meaning outside the house: they reveal nothing and save half a conversation.

  1. Health checks

Whatever runs the application (Docker, an orchestrator, a load balancer) needs two different answers:

// app/api/health/route.ts — is the process alive? If not, it must be restarted
import { connection } from 'next/server'

export async function GET() {
  await connection() // Without this, the GET reads nothing from the request and would be prerendered at build time
  return Response.json({ status: 'alive' }, { headers: { 'Cache-Control': 'no-store' } })
}

// app/api/health/ready/route.ts — can it serve visitors? If not, don't send them to it
import { sql } from 'drizzle-orm'
import { getDb } from '@/lib/db/client'
import { describeError, log } from '@/lib/log'

const TIMEOUT_MS = 2000

export async function GET() {
  const db = await getDb() // Includes io(): it isn't prerendered
  const headers = { 'Cache-Control': 'no-store' }

  try {
    await Promise.race([
      db.execute(sql`select 1`),
      new Promise((_, reject) =>
        setTimeout(() => reject(new Error('The database is not responding')), TIMEOUT_MS),
      ),
    ])
    return Response.json({ status: 'ready' }, { headers })
  } catch (error) {
    log('error', 'health.not-ready', describeError(error))
    return Response.json({ status: 'not-ready' }, { status: 503, headers })
  }
}
  • The first one doesn't query anything. If it checked the database, a PostgreSQL outage would make the orchestrator restart every instance, again and again, without fixing anything.
  • The second one checks only what's essential. Not the forecast or the mail: the website works without them.
  • They don't give away details: no versions, no addresses, no error messages. They're public, unless the load balancer closes them off.
  • Maintenance mustn't affect them. MAINTENANCE_MODE responds 503 to everything, and it would look as if the instance had died. In proxy.ts, first thing:
// proxy.ts, in proxy(), right after reading pathname
if (pathname === '/api/health' || pathname === '/api/health/ready') return NextResponse.next()

  1. What to watch and when to alert

A dashboard with forty charts is something nobody looks at. Start with four questions (known as the golden signals: traffic, errors, latency and saturation) and add the business ones:

Signal Where it comes from Alert if…
Errors exception per route More than 1% of requests for 5 minutes
Latency Traces, 95th percentile It doubles compared with the previous week
Saturation Pool connections, memory, CPU Above 80% for 10 minutes
Experience metric, 75th percentile (10-01) A route becomes "poor". The next day, not in the middle of the night
Bookings Count per hour Zero in an hour when there always are some
Mail mail.rejected Ten in a row
Sign-ins Rate limits exceeded A spike: it may be an attack
Tasks Last successful cleanup More than a day without one
Cache revalidation revalidation with a value Repeated on the same route

The bookings row is the most valuable, and it isn't technical. When the form stops working without throwing any error, the only signal is that something is missing.

Every alert that wakes someone up must be urgent, actionable and true. Everything else goes into a report. And every alert needs a page saying what to look at first and what can be done: at four in the morning nobody remembers what MAINTENANCE_MODE was.

From the outside, a service that requests / and /api/health/ready every minute detects what no internal log can tell you: that people can't get through.

Common Mistakes and Tips

  • --inspect open to the network, or in production.
  • Logging whole objects, bodies, cookies or addresses with parameters.
  • Logging a query's error.message without stripping the values.
  • Sentences instead of events: they can't be grouped.
  • Everything at error level.
  • Catching and staying silent. An empty catch is an invisible failure.
  • Sending errors without a timeout, or without await in onRequestError.
  • Publishing source maps without thinking about it.
  • Checking the database in the liveness probe.
  • Leaving NEXT_PRIVATE_DEBUG_CACHE switched on.
  • Opening spans before the first await in a prerendered component.
  • Alerts nobody can act on, or that go off every night.

Exercises

Exercise 1: triggering and following an error

Check the full circuit. Build, start, stop PostgreSQL and open a prerendered event page. What do you see and what don't you? Find in the log the error that matches the reference shown on screen. What do the two health checks say? Which part of the page still works, and why?

Solution

The event page is visible: title, date, poster and description come from the shell, which doesn't query anything. The availability and the booking fail and show their ErrorBoundary, each with its own reference. When signed in, AccountMenu fails too: if it doesn't have its own error boundary, the failure bubbles up to the public area's, which is a good reason to give it one.

In the log, one exception line per hole, with route: "/events/[slug]", kind: "render" and the same digest as on screen; the cause is the connection error. In addition, the browser.exception lines sent by ErrorNotice.

/api/health stays at 200, because restarting the process wouldn't fix anything. /api/health/ready responds 503. If every instance stopped receiving visitors because of that, not even the shell would be served: with an application like this one, decide whether you'd rather keep sending traffic during a database outage.

Exercise 2: reviewing a log

Find the problems and rewrite it with log.

export async function signIn(returnTo: string, previous: SignInState, formData: FormData) {
  console.log('Sign-in attempt', Object.fromEntries(formData), await headers())
  try {
    // …
  } catch (error) {
    console.log('ERROR!!! user ' + formData.get('email') + ' ' + JSON.stringify(error))
  }
  if (!correct) console.error('Wrong password for ' + email)
}

Solution

if (!(await withinLimits(signInLimits(email, await getIp())))) {
  log('warn', 'sign-in.limited', { account: hashToken(email).slice(0, 12) })
  return reject(TOO_MANY)
}

// … and after checking
if (!account || !correct) {
  log('info', 'sign-in.failed', { account: hashToken(email).slice(0, 12) })
  return reject(BAD_CREDENTIALS)
}

The original writes the password, the session cookie and the email address. The catch swallows everything, including the special redirect error, and JSON.stringify(error) produces {}, so it doesn't even help. A wrong password isn't an application error: it's information, and only a spike deserves attention.

The truncated hash lets you see that many attempts target the same account without writing the email address. It isn't anonymous, because anyone with a list of email addresses can compute it, so it's still pseudonymized personal data, with its deletion period. If you're not going to use it, don't store it.

Exercise 3: designing an alert

One Saturday, between 18:00 and 22:00, nobody could book: a CSP change blocked the script that hydrates the form in Firefox. There were no errors on the server. Which signals from this lesson would have shown it, which would have alerted first, and what would you add so it doesn't reach production?

Solution

The /api/csp reports would have shot up from the first minute, with the directive and the page; it's the fastest signal, if there's an alert on their rate rather than on each one, because there's always noise. browser.exception too, if the block produced an error. Firefox's web metrics would have disappeared, since WebMetrics wasn't running either: another absence. And the booking count would drop without reaching zero, because of the other browsers, so a "zero" alert wouldn't have fired; a comparison with the same day the previous week would have.

The form, receiving a Server Action directly, should have worked without hydrating (06-01). It's worth checking why it didn't: perhaps someone wrapped it in a client function.

To keep it from reaching production: the booking test already carries @all and runs in Firefox, and watchConsole turns the block into a failure (10-04). What was missing was publishing the new CSP in report-only mode first (08-05).

Conclusion

Debugging is understanding what's in front of you, with breakpoints on each side and certainty about what comes from the cache. Observing is being able to understand what you didn't see: named events without personal data, onRequestError and instrumentation-client.ts so that no error gets lost, traces that say where the time went, health checks with two different answers and few alerts, but true ones. The reference a person sees, the log line and the trace now tell the same story.

That's the end of module 10. AgendaViva measures itself, has a budget, is tested at every level and can tell when something is wrong. It's missing pieces we've been leaving for the end (editing and canceling what's been published, closing off the dashboard) and, above all, getting out of your machine. Module 11, Final Project and Deployment, brings them together, and it starts by reviewing the whole and its decisions in Planning and Project Architecture.

© Copyright 2026. All rights reserved