0
0
RemixDebug / FixBeginner · 4 min read

How to Handle 404 Errors in Remix: Simple Guide

In Remix, handle 404 errors by using a CatchBoundary in your route module. This special export catches thrown responses like 404 and lets you render a custom message or UI for not found pages.
🔍

Why This Happens

A 404 error occurs when a user tries to visit a page that does not exist in your Remix app. If you don't handle this error, Remix will show a default error screen or a blank page, which is confusing for users.

Here is an example of broken code where no CatchBoundary is defined, so Remix cannot show a friendly 404 page:

javascript
export async function loader({ params }) {
  const data = await fetchData(params.id);
  if (!data) {
    throw new Response('Not Found', { status: 404 });
  }
  return data;
}

// No CatchBoundary defined here
Output
Error: Not Found Status: 404 (No custom UI, default Remix error screen shown)
🔧

The Fix

To fix this, add a CatchBoundary export in your route file. Remix will use this to catch thrown responses like 404 and render your custom UI. This improves user experience by showing a clear message.

jsx
import { useCatch } from '@remix-run/react';

export async function loader({ params }) {
  const data = await fetchData(params.id);
  if (!data) {
    throw new Response('Not Found', { status: 404 });
  }
  return data;
}

export function CatchBoundary() {
  const caught = useCatch();
  if (caught.status === 404) {
    return <div><h1>Page Not Found</h1><p>Sorry, we couldn't find what you were looking for.</p></div>;
  }
  throw new Error(`Unexpected caught response with status: ${caught.status}`);
}
Output
<h1>Page Not Found</h1> <p>Sorry, we couldn't find what you were looking for.</p>
🛡️

Prevention

Always define a CatchBoundary in your routes where you expect errors like 404. This ensures users see friendly messages instead of confusing errors. Use consistent error handling patterns across your app.

Also, test your routes by visiting invalid URLs to confirm your 404 UI appears correctly.

⚠️

Related Errors

Other common errors you might handle similarly include 401 (Unauthorized) and 500 (Server Error). Use CatchBoundary to catch these and show appropriate messages.

For unexpected errors, use ErrorBoundary to catch runtime exceptions and display fallback UI.

Key Takeaways

Use a CatchBoundary export in Remix routes to handle 404 errors gracefully.
Throw a Response with status 404 in your loader when data is missing.
Render user-friendly messages inside CatchBoundary for better UX.
Test invalid URLs to ensure your 404 page works as expected.
Use ErrorBoundary for unexpected runtime errors separate from 404 handling.