Monitoring and Observability for Next.js
A Next.js application in production is a distributed system wearing a familiar face: server components, route handlers, background jobs, a database, third-party APIs, and a browser that can fail in all of them. When something breaks, the question is never "is it broken" â users tell you that â but "where, for whom, and since when." Observability is the discipline of being able to answer those three questions without deploying a debug build.
This lesson covers the pieces a Next.js team actually needs: logs that stay queryable after they leave your machine, a correlation id that ties a browser session to a server trace, error capture on both sides of the boundary, and alerting tuned so the on-call engineer still reads it in month three.
Prerequisites
- !Route handlers, middleware, and environment variables
- !Familiarity with JSON and basic log querying
- !A deployed Next.js application you can access
What You'll Learn
- 1Emit structured logs that a query engine can filter
- 2Propagate a request id from middleware through every log line
- 3Capture client errors, server errors, and build failures in one workflow
- 4Choose alert thresholds from service objectives rather than from noise
Three signals, three different questions
Teams often buy a single tool and expect it to answer everything. Each signal answers a different question, and conflating them is why dashboards grow while understanding does not.
| Signal | The question it answers | Granularity | Typical retention | Cost per unit |
|---|---|---|---|---|
| Logs | What exactly happened here? | One event, rich context | Days to weeks | High at volume |
| Metrics | Is it healthy overall, and since when? | Aggregated, time-series | Months | Low |
| Traces | Where did this one request spend its time? | Per request, spans | Hours to days | Medium |
The practical starting point for a small team is logs plus metrics: structured log lines that can be aggregated into metrics, and a handful of metrics that decide whether anyone is paged. Traces become worth the setup cost once you have more than one network hop between the user's request and the data they asked for.
Structured logging that survives aggregation
A log line is only useful if something can filter on it later, which means the payload matters more than the prose. Emit JSON with a fixed set of fields, keep the human-readable sentence short, and never put unbounded user input at the top level â a card number or a full URL with a token in it will end up indexed, retained, and visible to everyone with read access.
// lib/logger.js
const LEVELS = { debug: 10, info: 20, warn: 30, error: 40 };
const MIN_LEVEL = LEVELS[process.env.LOG_LEVEL || 'info'] || 20;
const SENSITIVE = new Set(['password', 'token', 'authorization', 'cookie', 'card']);
function redact(value) {
if (Array.isArray(value)) return value.map(redact);
if (value && typeof value === 'object') {
return Object.fromEntries(
Object.entries(value).map(([key, val]) =>
SENSITIVE.has(key.toLowerCase()) ? [key, '[redacted]'] : [key, redact(val)]
)
);
}
return value;
}
export function log(level, message, fields = {}) {
if (LEVELS[level] < MIN_LEVEL) return;
const entry = {
level,
message,
time: new Date().toISOString(),
service: 'web',
...redact(fields),
};
const line = JSON.stringify(entry);
if (LEVELS[level] >= LEVELS.error) console.error(line);
else console.log(line);
}
export const logger = {
debug: (message, fields) => log('debug', message, fields),
info: (message, fields) => log('info', message, fields),
warn: (message, fields) => log('warn', message, fields),
error: (message, fields) => log('error', message, fields),
};
Two design choices pay off immediately. Redaction happens at the logger, not at each call site, because a call site will eventually forget. And the level filter reads an environment variable, so development can run verbose while production keeps only what matters â but note that a level below the minimum costs the string formatting too, so debug calls should stay cheap or be guarded.
Correlating one request across the app
Individual lines are trivia until you can thread them together. Assign a request id at the edge of the application â middleware is the natural place â forward it inbound if a gateway already produced one, and attach it to every log line, response header, and downstream call.
// middleware.js
import { NextResponse } from 'next/server';
export function middleware(request) {
const incoming = request.headers.get('x-request-id');
const requestId = incoming || crypto.randomUUID();
const requestHeaders = new Headers(request.headers);
requestHeaders.set('x-request-id', requestId);
const response = NextResponse.next({ request: { headers: requestHeaders } });
response.headers.set('x-request-id', requestId);
return response;
}
export const config = { matcher: '/((?!_next/static|_next/image|favicon.ico).*)' };
// app/api/orders/route.js
import { logger } from '@/lib/logger';
export async function GET(request) {
const requestId = request.headers.get('x-request-id') || 'unknown';
const started = Date.now();
try {
const orders = await fetchOrders();
logger.info('orders.listed', { request_id: requestId, count: orders.length, ms: Date.now() - started });
return Response.json(orders);
} catch (error) {
logger.error('orders.failed', {
request_id: requestId,
code: error.code || 'unknown',
ms: Date.now() - started,
});
return Response.json({ error: 'Unable to load orders' }, { status: 500 });
}
}
With the id echoed in the response header, a bug report that includes a screenshot of the network tab is enough to find every line that request produced. Pass the same header to outbound fetches as well: when your API calls a payments provider that supports request correlation, the id follows the call across the boundary and support tickets become answerable instead of arguable.
Capturing errors where they actually happen
Errors surface in three places, and each needs its own capture. Server-side render failures and route handler exceptions belong to the framework's error files; client runtime errors need a component boundary; and asynchronous failures â unhandled rejections, failed image loads, worker crashes â belong to a global handler that no component tree owns.
// app/global-error.js
'use client';
export default function GlobalError({ error, reset }) {
return (
<html lang="en">
<body>
<h2>Something went wrong</h2>
<button onClick={reset}>Try again</button>
</body>
</html>
);
}
// components/ReportError.jsx
'use client';
import { useEffect } from 'react';
export function ErrorReporter() {
useEffect(() => {
function onRejection(event) {
fetch('/api/client-errors', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
kind: 'unhandledrejection',
message: String(event.reason && event.reason.message || event.reason),
stack: event.reason && event.reason.stack,
url: window.location.href,
}),
keepalive: true,
});
}
window.addEventListener('unhandledrejection', onRejection);
return () => window.removeEventListener('unhandledrejection', onRejection);
}, []);
return null;
}
Server-side, wrap your database and provider calls so the error is logged once with context before it is converted into a friendly response â an exception that reaches the framework twice produces two confusing entries. Client-side, report the message, the component stack if the boundary provides one, the route, and the release version, because an error from a build you shipped two days ago is a very different incident from one that started this morning. Deduplicate on the client: a component that throws on every render will otherwise send thousands of identical reports in seconds.
Metrics worth alerting on
Metrics should be few, stable, and tied to what users experience. Latency averages are the classic trap â a route that is fast for ninety-nine users and broken for one averages to fine. Alert on percentiles and on error ratios instead.
| Metric | Why it matters | Example threshold |
|---|---|---|
| Request error ratio | Direct signal of broken requests | Above 1 percent over 5 minutes |
| Latency 95th percentile | Reflects the unhappy user, not the average | Above 800 ms for 10 minutes |
| Time to first byte on key routes | Catches cold starts and database stalls | Above 1.5 seconds for 5 minutes |
| Cache hit ratio | Dropping hit ratio predicts a cost and latency spike | Below 80 percent for 15 minutes |
| Queue depth or job age | Reveals work nobody is consuming | Oldest job older than 10 minutes |
| Client-side error rate | Catches failures the server never sees | Above 0.5 percent of sessions |
Keep the metric names stable across releases and label them with the route or handler rather than the raw path, so a dynamic segment does not create a new series per id.
Alerting people do not mute
An alert should arrive when a human can do something, and it should describe the objective it protects. The reliable pattern is to define a small number of service level objectives â say, 99.9 percent of requests succeeding within 800 milliseconds over a rolling month â and page when the error budget is burning faster than it can be replenished. Burn-rate alerts fire on the trend rather than a single spike, which means a brief deploy-time blip stays silent while a slow regression pages before customers write in.
Equally important is what not to alert on: CPU percentages without a user impact, single-instance restarts that are part of normal operation, and any threshold that has been acknowledged and silenced more than twice a week. Every alert that reliably produces no action trains the rotation to ignore the next one. Review the alert list quarterly, delete what nobody acted on, and write the runbook link into the alert payload so the responder starts with a checklist rather than a search engine.
What the platform already gives you
Before adding infrastructure, take what the platform provides. Managed hosting surfaces per-invocation logs, function duration, and cold-start counts with no code changes. OpenTelemetry instrumentation, loaded from a single instrumentation file, produces traces that can be exported to any backend that speaks the protocol, which means your logging choice is not a one-way door. Real user monitoring catches what synthetic checks cannot: a third-party script that blocks interaction on one specific device class. Wire those three sources together and most incidents become a five-minute exercise â identify the release, filter by request id, read the correlated lines â rather than an afternoon of guesswork.
Common Mistakes
Logging free-text sentences that nothing can filter on
Fix: Emit JSON with a stable field set so queries and alerts can key on structure.
Putting secrets or full URLs with tokens into log fields
Fix: Redact centrally in the logger and keep user identifiers hashed or truncated.
Alerting on averages instead of percentiles and error ratios
Fix: Averages hide the affected minority; alert on the tail and on the failure rate.
Client errors that fire on every render of a broken component
Fix: Deduplicate by message and route, and cap reports per session.
No correlation id, so each incident means grepping three systems
Fix: Assign the id in middleware, echo it to the client, and propagate it downstream.
Alerts nobody has acted on for weeks
Fix: Delete or re-threshold them; unactionable alerts train the rotation to ignore everything.
Best Practices
- Log from one shared logger that owns redaction, levels, and formatting
- Echo the request id in response headers so bug reports come with a lookup key
- Record duration and outcome for every outbound call to a database or provider
- Define service level objectives first, then derive alert thresholds from error budget
- Attach the release version to every log line and error report to make bisecting trivial
- Review and prune alerts quarterly alongside the runbook they link to
Interview Questions
Q1: How do you trace a user-reported failure from the browser to the database?
Take the request id from the response header or network tab, filter logs by that id, and follow the same id on downstream calls; the release version narrows it to a deploy.
Q2: Why should latency alerts use a percentile rather than a mean?
A mean hides the slow tail, so a route failing for a small share of users can still look healthy while those users experience a broken page.
Q3: What is an error budget and how does it drive alerting?
It is the inverse of the service level objective â the allowed fraction of failed or slow requests. Paging when the budget burns faster than it refills ties alerts to user impact.
Q4: Where do client-side errors go in a Next.js app?
Into an error boundary for render failures, plus a global handler for unhandled rejections, both posted to a capture endpoint with route and release context.
Key Takeaways
- Logs answer what happened, metrics answer whether it is healthy, traces answer where the time went.
- Structured JSON with a stable field set and central redaction is the foundation everything else queries.
- A request id assigned in middleware turns three systems of trivia into one investigation.
- Capture errors at the boundary, in the client tree, and in a global asynchronous handler.
- Alert on percentiles, error ratios, and burn rate â never on averages or raw CPU.
- Every alert needs an owner, a threshold tied to an objective, and a runbook link, or it should be deleted.