
On this page
Table of Contents
How to Debug Production Errors in Next.js (App Router Guide)
Your Next.js application works locally. The production build succeeds, and your deployment goes live.
Then someone opens a page and sees:
Application error: a client-side exception
has occurred while loading your application.Or a Server Component fails and displays a generic message with an error digest.
Neither message immediately tells you which line of application code caused the problem.
Production debugging is different from debugging in development. Errors may be minified, server details are intentionally hidden from browsers, and problems can depend on environment variables, deployment configuration, user sessions, or external services.
The solution is to follow a repeatable debugging process.
In this guide, you'll learn how to debug production errors in Next.js using browser tools, server logs, error digests, error boundaries, monitoring services, and local production builds.
The examples focus on the Next.js App Router and applications deployed on Vercel, although many techniques also apply to other hosting platforms.
1. Understand Why Next.js Production Errors Look Different
During development, Next.js provides detailed error messages and debugging tools.
You may see the relevant source file, component stack, or code location.
Production environments behave differently for two important reasons.
Client-side JavaScript is optimized
Production JavaScript is usually transformed and minified.
This can make stack traces difficult to read without source maps.
A browser error may reference a generated asset rather than the original TypeScript component.
Server-side errors hide sensitive details
Next.js intentionally limits the error details sent to browsers when certain Server Component failures occur in production.
This prevents internal error messages from accidentally revealing sensitive information.
Instead, a production error may include a digest identifier.
The full details must be investigated through appropriate server-side logging or monitoring.
Important: A digest is a diagnostic identifier, not a guarantee that every hosting provider automatically saves a searchable stack trace.
2. First Identify Where the Error Occurred
Before changing code, determine which part of the application failed.
Three common categories are client-side errors, server-side errors, and deployment/build errors.
Client-side errors
These happen in JavaScript running in the browser.
Possible causes include:
- Accessing a property on
undefined - Invalid component state
- Browser-only APIs used incorrectly
- Failed third-party widget initialization
- Hydration problems
Start with the browser's Console and Network panels.
Server-side errors
These occur while rendering server-side content or processing server operations.
Possible causes include:
- Database connection failures
- Missing environment variables
- Invalid authentication state
- Unexpected API responses
- Exceptions in Server Components or server-side functions
Start with your hosting provider's runtime logs.
Build-time errors
These prevent the application from being deployed successfully.
Common causes include:
- TypeScript errors
- Missing dependencies
- Invalid imports
- Build-time data fetching failures
- Configuration problems
Start with deployment Build Logs.
A useful troubleshooting rule
Don't treat every production error as a browser problem.
The first step is identifying the failed stage and collecting its actual error evidence.
3. Use Vercel Logs to Investigate Server Errors
If your Next.js application runs on Vercel, you can inspect server execution logs from the Vercel dashboard.
Open your project and navigate to Logs.
You can filter activity using information such as:
- Deployment
- Request path
- HTTP status code
- Error level
- Time range
- Request ID
This makes it easier to investigate a specific failing route instead of searching through unrelated application activity.
Example: A server-side request fails
Imagine your application calls an external API:
const response = await fetch(
"https://api.example.com/products"
);
const products = await response.json();The code assumes the response is valid JSON.
But an upstream service may return an HTML error page or another unexpected response.
Calling response.json() can then throw an exception.
A safer approach is to check the HTTP response before parsing.
async function getProducts() {
const response = await fetch(
"https://api.example.com/products",
{ cache: "no-store" }
);
if (!response.ok) {
throw new Error(
`Product API failed with status ${response.status}`
);
}
const contentType =
response.headers.get("content-type") ?? "";
if (!contentType.includes("application/json")) {
throw new Error(
"Product API returned an unexpected content type"
);
}
return response.json();
}This example makes failures easier to classify.
It doesn't guarantee the returned JSON has the correct structure. For critical integrations, validate the response schema as well.
Check the correct logs
If a deployment fails to build, inspect Build Logs.
If the deployment succeeds but a Server Component, Route Handler, or other server operation fails, inspect Runtime Logs.
Also check that you're viewing the correct production or preview deployment.
4. Understand Next.js Error Digests
A production Server Component error may include a diagnostic identifier:
An error occurred in the Server Components render.
Digest: 123456789The number above is illustrative.
Next.js generates a digest for certain server-side errors.
It can help associate a browser-visible failure with server-side diagnostic information.
How to use a digest
When investigating a reported error:
- Record the digest shown in the browser, if available.
- Record the approximate time of the failure.
- Note the route and relevant deployment.
- Open the matching server runtime logs.
- Search for the digest or other associated error information.
- Inspect the actual exception and its surrounding request context.
The digest alone may not be enough.
If your application doesn't capture useful server-side errors, you may need improved instrumentation.
Why not expose the full server error to users?
An internal error could contain database details, implementation information, or other sensitive content.
A public error page should not expose that information.
Instead, provide a safe message to the user and keep detailed diagnostics in trusted logging systems.
5. Add Error Boundaries with error.tsx
Next.js App Router supports route-segment error boundaries.
Create an error.tsx file to display a fallback interface when an unexpected error occurs within the supported segment boundary.
For example:
src/
└── app/
└── dashboard/
├── page.tsx
└── error.tsxHere is a basic implementation:
"use client";
import { useEffect } from "react";
export default function DashboardError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
// Replace with your error-monitoring integration.
console.error(error);
}, [error]);
return (
<main className="mx-auto max-w-xl p-8 text-center">
<h2 className="text-xl font-semibold">
Unable to load the dashboard
</h2>
<p className="mt-3 text-gray-600">
Something went wrong while loading this page.
</p>
<button
type="button"
onClick={() => reset()}
className="mt-5 rounded bg-black px-4 py-2 text-white"
>
Try again
</button>
</main>
);
}Why is "use client" required?
Next.js error boundaries are Client Components.
They need browser-side behavior to display fallback UI and support recovery interactions.
What does reset() do?
The reset() function attempts to render the affected boundary again.
This can help when an error was temporary.
For example, a transient data-fetching failure may succeed on a subsequent attempt.
However, retrying does not fix a missing environment variable, invalid database schema, or permanent application bug.
What error boundaries don't catch
An error.tsx file is not a universal exception handler.
It doesn't automatically handle every error in event handlers, standalone Route Handlers, or arbitrary asynchronous operations.
Expected validation failures should generally be handled explicitly rather than thrown as unexpected exceptions.
Handling root layout errors
For errors involving the root layout or template, Next.js provides global-error.tsx.
Unlike an ordinary route-segment fallback, a global error component must include its own <html> and <body> elements.
Version note: Next.js error-handling APIs evolve. The established reset interface shown above is documented in the error file-convention reference. Check your installed version's documentation when using newer or experimental recovery APIs.
6. Handle Expected Errors Without Crashing the Page
Not every unsuccessful operation is a programming bug.
Consider a login form.
An incorrect password is an expected failure.
A missing database table is not.
Treating both situations as uncaught exceptions makes debugging harder and creates a poor user experience.
Example: Handle an API failure explicitly
type Result<T> =
| { success: true; data: T }
| { success: false; message: string };
async function loadProduct(
productId: string
): Promise<Result<unknown>> {
try {
const response = await fetch(
`/api/products/${encodeURIComponent(productId)}`
);
if (response.status === 404) {
return {
success: false,
message: "Product not found",
};
}
if (!response.ok) {
return {
success: false,
message: "Unable to load product",
};
}
return {
success: true,
data: await response.json(),
};
} catch {
return {
success: false,
message: "Network request failed",
};
}
}This gives the calling UI a result it can display without crashing.
The unknown type is intentional here. A complete application should validate the API response and replace it with a proper product type.
For unexpected server failures, log the diagnostic details on the server while returning a safe message to the client.
7. Debug Hydration Errors in Next.js
Hydration errors are among the more confusing problems in server-rendered React applications.
A typical message looks like this:
Hydration failed because the server rendered HTML
didn't match the client.Hydration occurs when React connects browser-side interactivity to HTML generated on the server.
Problems can occur when the browser's initial render produces different output from the server.
Cause 1: Rendering the current time
Consider:
export default function Timestamp() {
return <p>{new Date().toLocaleString()}</p>;
}The server and browser may format dates using different time zones, locales, or execution times.
That can produce mismatched text.
Fix: Render a stable timestamp
One approach is to send a consistent ISO timestamp and format it using a known locale and time zone.
export default function Timestamp({
isoDate,
}: {
isoDate: string;
}) {
const formatted = new Intl.DateTimeFormat("en-US", {
timeZone: "UTC",
dateStyle: "medium",
timeStyle: "short",
}).format(new Date(isoDate));
return <time dateTime={isoDate}>{formatted}</time>;
}The isoDate value should come from stable application data rather than independently calling new Date() during both server and browser renders.
If you need the visitor's local time zone, render a stable initial value and apply browser-specific formatting after hydration.
Cause 2: Calling Math.random() during render
This can also create inconsistent initial output:
export default function RandomNumber() {
return <p>{Math.random()}</p>;
}The server and client may generate different values.
Use a stable value supplied by the server, or generate client-only values after hydration when appropriate.
For IDs needed by React components, prefer useId() rather than using a random value during rendering. useId() is not a replacement for database record IDs.
Cause 3: Invalid HTML nesting
For example:
export default function Example() {
return (
<p>
Description
<div>Additional content</div>
</p>
);
}A <div> should not be nested inside a <p> element.
The browser may correct invalid HTML, producing a DOM structure different from what React expects.
Use valid HTML instead.
Cause 4: Browser extensions
Some extensions modify page content before React hydrates.
If the error is difficult to reproduce, testing in a clean browser profile can help identify whether a browser extension contributes to the mismatch.
Don't assume every hydration error is caused by an extension.
A practical hydration debugging process
- Reproduce the issue using the same route and input data.
- Read the browser console warning.
- Identify the component or element mentioned.
- Check render-time dates, random values, and browser-specific state.
- Inspect HTML nesting.
- Test in a clean browser session.
- Compare development and production behavior.
Avoid using suppressHydrationWarning simply to hide a genuine mismatch. It is an escape hatch for narrowly understood situations, not a general repair tool.
8. Reproduce a Production Build Locally
Sometimes a problem appears only after production compilation.
Running the development server may not reproduce it.
A useful check is to build and start the application in production mode.
npm run build
npm run startFor a typical Next.js project, these scripts execute next build and next start.
You can then open the local production server and reproduce the affected route.
Why this helps
A production build may reveal issues involving:
- Build-time environment variables
- Server and Client Component boundaries
- Production rendering behavior
- Dynamic imports
- Minified code
- Static generation
Important limitations
A local production build is not identical to Vercel.
Your machine may use different:
- Operating system
- Node.js version
- Environment variables
- Network configuration
- External database access
- Hosting runtime behavior
If the problem only happens on Vercel, compare the deployment configuration and inspect the hosted runtime logs.
Also, don't expect a local production build to show the same detailed error overlay as next dev.
9. Debug Environment Differences
Environment mismatches are a common reason applications work locally but fail after deployment.
For example, your local .env.local may contain:
DATABASE_URL=your_database_connection_stringBut the production environment may not define DATABASE_URL.
The result can be a database initialization failure.
Validate required variables
For server-only values, use explicit validation:
export function getDatabaseUrl() {
const value = process.env.DATABASE_URL;
if (!value) {
throw new Error(
"DATABASE_URL environment variable is missing"
);
}
return value;
}Keep this helper in server-only code. Do not import it into a Client Component.
Compare the correct environments
Check whether each variable exists in:
- Your local environment
- Vercel Preview
- Vercel Production
Also confirm that the values point to the correct external services.
For example, a production Supabase project may have different tables, RLS policies, or credentials from your development project.
Never print full database URLs, secret keys, access tokens, or private environment variable values in logs.
A safer diagnostic is to report whether a required setting exists, not its secret value.
10. Use Structured Logging Instead of Random Console Messages
A log such as:
console.log("Something failed");doesn't provide enough information to investigate a production problem.
Better logs identify what operation failed and where.
Example: Structured server-side error logging
export function logOperationError(
operation: string,
error: unknown,
requestId: string
) {
const message =
error instanceof Error
? error.message
: "Unknown error";
console.error(
JSON.stringify({
event: "operation_failed",
operation,
requestId,
message,
timestamp: new Date().toISOString(),
})
);
}Example usage:
try {
await updateInventory();
} catch (error) {
logOperationError(
"update_inventory",
error,
requestId
);
throw error;
}Here, updateInventory and requestId represent values supplied by the surrounding application.
This helper is an illustrative logging pattern rather than a standalone runnable route.
What should you log?
Useful fields may include:
- Event name
- Operation
- Route
- Request ID
- Timestamp
- Safe error classification
Avoid logging passwords, authorization headers, session cookies, API secrets, payment details, or raw sensitive user data.
Even exception messages can contain sensitive values, so production logging should include an appropriate redaction policy.
A stable request ID can be especially useful for correlating the browser request with the server-side failure.
11. Add Production Error Monitoring
Manually searching logs is useful when investigating an individual issue.
For ongoing applications, error monitoring can help collect failures automatically.
Services such as Sentry can capture exceptions, group related errors, and provide diagnostic context.
The exact information available depends on the SDK configuration, source maps, sampling, and privacy settings.
Setting up Sentry in Next.js
Start with the official Next.js integration documentation:
https://docs.sentry.io/platforms/javascript/guides/nextjs/
Follow the setup instructions appropriate to your installed Next.js and SDK versions.
After setup:
- Confirm server-side exceptions are captured.
- Confirm client-side exceptions are captured.
- Review source-map configuration.
- Verify that the monitoring project receives events.
- Configure alerts for important errors.
- Review data collection and privacy settings.
Why source maps matter
Production JavaScript is often minified.
Source maps can help monitoring tools associate generated code with your original source files.
Without suitable source maps, a stack trace may point to compiled JavaScript instead of the component you wrote.
Configure source-map handling carefully and avoid unintentionally exposing source code through public assets.
Test monitoring before relying on it
A successful installation does not prove error collection is working.
Use a controlled test error in a non-production environment and verify that the monitoring service receives the expected event.
Don't intentionally throw test exceptions on a live customer-facing route.
12. Use Next.js Instrumentation for Server Error Reporting
Next.js provides an instrumentation.ts convention for integrating observability tools.
For server-side error reporting, you can define an onRequestError handler.
For example:
// src/instrumentation.ts
import type { Instrumentation } from "next";
export const onRequestError:
Instrumentation.onRequestError = async (
error,
request,
context
) => {
console.error(
JSON.stringify({
event: "nextjs_request_error",
digest: error.digest,
route: context.routePath,
message: error.message,
})
);
};This demonstrates the server-side instrumentation hook.
The application should apply appropriate redaction and log-retention policies before using a similar handler in production.
You can also integrate an external monitoring provider instead of relying on console output.
Important behavior
onRequestError handles errors captured through the relevant Next.js server request lifecycle.
It does not replace browser-side monitoring or every other error-handling mechanism.
For client-side monitoring, Next.js also provides the instrumentation-client.ts convention.
Use the appropriate monitoring integration for each runtime.
13. A Practical Next.js Production Debugging Checklist
When something fails in production, follow this sequence.
Step 1: Capture the evidence
Record the exact URL, time, error message, and affected deployment.
If possible, identify whether the failure affects one user or everyone.
Step 2: Identify the failure category
Is it a build failure, browser exception, server exception, API failure, or routing problem?
Step 3: Open the relevant diagnostics
For browser errors, check DevTools Console and Network.
For server errors, inspect runtime logs and error digests where available.
For build errors, inspect deployment build logs.
Step 4: Check environment differences
Compare relevant Node.js versions, configuration, environment variables, and deployed dependencies.
Do not expose secret values during troubleshooting.
Step 5: Reproduce the issue safely
Use local production mode or an isolated Preview environment where possible.
Avoid testing destructive actions against real customer data.
Step 6: Fix the actual cause
Correct the failing operation rather than hiding its exception.
Do not disable TypeScript checks, authorization, or production logging simply to make an error disappear.
Step 7: Prevent the same problem from returning
When appropriate, add a regression test, improve error handling, or introduce monitoring for the failure category.
Step 8: Confirm the fix in production
A successful deployment is only the beginning.
Verify the affected route or operation again and check that error reports stop for the corrected scenario.
Common Production Debugging Mistakes
Relying only on the browser error message. Server-side details may be intentionally hidden.
Treating a digest as a complete diagnostic report. It needs to be correlated with logs or monitoring evidence.
Logging sensitive data. Production error reports can become a privacy and security risk if secrets or personal information are recorded.
Catching every exception and returning success. This hides failures instead of fixing them.
Using an error boundary for all failures. Expected errors, network operations, and event-handler failures may need separate handling.
Ignoring hydration warnings. A hydration mismatch can indicate genuinely inconsistent rendering.
Testing only with next dev. Production behavior may differ from development mode.
Assuming monitoring is working without testing it. Verify that test events reach the intended monitoring project.
Final Thoughts
Debugging production errors in Next.js becomes easier when you separate the problem into clear stages.
Start by identifying whether the failure happened during building, server execution, or browser rendering.
Use Vercel logs and Next.js digests to investigate server-side failures. Use browser DevTools and source maps to understand client-side issues. Add error boundaries where they improve recovery, and handle expected errors explicitly.
For recurring production issues, structured logging and monitoring can provide the context needed to investigate problems without relying on screenshots from users.
Most importantly, verify the actual cause before declaring an issue fixed.
A reliable debugging workflow isn't about eliminating every error. It's about making failures easier to detect, understand, reproduce, and resolve.
Related CodeWithLogs Guides
- Common Vercel Deployment Errors and Their Solutions
- How to Deploy a Next.js App to Vercel
- How to Improve Next.js Website Performance
- Supabase Production Errors and Fixes
- Error Decoder Tool
Official Documentation
Keep the conversation useful
Found a different result?
Include your framework version, the error, and the steps to reproduce it. Specific details help improve the article for the next reader.
Send a correction or question

