Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 39 ยท Error Handling and Boundaries

Unexpected Errors and Logging

Handle real bugs in Remix and React Router: the server handleError hook, logging without leaking secrets, request IDs, safe messages and reporting client errors.

Expected failures like a missing record are thrown deliberately. Unexpected errors are the rest: a typo, a null you did not guard against, a database that went away. You cannot write a branch for each one, but you can decide three things in advance: what the visitor sees, what you record for yourself, and how you find the failing request later. This lesson covers all three in a framework-mode app.

What the framework does by default

When a loader, action or component throws a normal Error (not a response), the router catches it, finds the nearest boundary and responds with status 500. In production the message is hidden from the browser on purpose: the client only learns that an error occurred. During development you see the message and stack to debug faster. This default protects you, because error messages often contain SQL, file paths or secrets.

That means your boundary cannot rely on error.message being available in production. Write a generic message for unexpected errors and put the detail in your logs.

The server handleError hook

The file app/entry.server.tsx can export handleError. React Router calls it for every unexpected error on the server (not for thrown responses), so it is the one place to log:

TSX
// app/entry.server.tsx (read-only, React Router framework mode)
import type { HandleErrorFunction } from "react-router";

export const handleError: HandleErrorFunction = (error, { request }) => {
  // Requests that the browser cancelled are not bugs.
  if (request.signal.aborted) return;

  console.error(
    JSON.stringify({
      level: "error",
      time: new Date().toISOString(),
      method: request.method,
      url: new URL(request.url).pathname,
      message: error instanceof Error ? error.message : String(error),
      stack: error instanceof Error ? error.stack : undefined,
    })
  );
};

Two details matter. Skip aborted requests, since a user closing a tab mid-request would otherwise flood your log. And log the path only, not the full URL: query strings can carry tokens or email addresses.

Structured logs and request IDs

Plain text logs are hard to search. Write one JSON object per line (structured logging) with a stable set of keys, and attach a request ID so one visitor's report ("it broke at 14:02") can be matched to one log line. Generate an ID per request in entry.server.tsx or a server middleware, return it in a response header and show it on the error page.

Node.js Stand-in: a structured logger with a redactor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Errors in the browser

Route boundaries catch render errors in the browser, but nothing is logged to your server because the code ran on the visitor's machine. To learn about them, report from the boundary:

TSX
import { useEffect } from "react";

export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
  useEffect(() => {
    if (error instanceof Error) {
      navigator.sendBeacon("/api/client-errors", JSON.stringify({ message: error.message }));
    }
  }, [error]);

  return <p>Something went wrong.</p>;
}

sendBeacon queues a small POST that survives page unloads. The receiving route should be rate-limited and should never trust the payload, since anyone can post to it. Many teams use a hosted error tracker instead; whichever you choose, call it from handleError on the server and from the boundary in the browser.

Making errors safer to handle

  • Wrap external calls. Catch errors from a payment or email API near the call and convert them to something meaningful (throw data("Payment service unavailable", { status: 503 })).
  • Preserve the cause. throw new Error("Could not load profile", { cause: err }) keeps the original for your logs.
  • Fail fast on config. Validate environment variables at startup, not at the first request that needs them.
  • Do not catch and ignore. An empty catch {} hides the very information you need.
Node.js Stand-in: wrapping with a cause

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In production, what does the browser receive when a loader throws a normal Error?

    Messages can leak secrets, so production responses hide them. You log the detail on the server.
  2. 2. Where do you log every unexpected server error in one place?

    handleError is called for each unexpected server error, which makes it the central place to log or report.
  3. 3. Why skip logging when request.signal.aborted is true?

    Closing a tab or navigating away aborts the request and often raises harmless errors.
  4. 4. Which is safest to log?

    Paths and IDs identify the request without exposing credentials or personal data.
  5. 5. What does the cause option of Error do?

    new Error(msg, { cause }) lets you show a friendly message while preserving the real reason.

Summary

  • Unexpected errors give status 500 and hide their message in production.
  • Log centrally in handleError; skip aborted requests; log paths, not full URLs.
  • Use structured JSON logs, request IDs and a redactor so secrets never reach logs.
  • Report browser errors from the boundary with sendBeacon or a tracker.
  • Wrap external failures and keep the original as cause.

Next: Cookies and Sessions