How to Handle 404 Errors in Remix: Simple Guide
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:
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
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.
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}`); }
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.