0
0
RemixHow-ToBeginner ยท 3 min read

How to Create a Catch All Route in Remix

In Remix, create a catch all route by naming a route file with $ followed by *.tsx or *.jsx (e.g., $*.tsx). This file will match all paths not matched by other routes, acting as a fallback or 404 page.
๐Ÿ“

Syntax

To create a catch all route in Remix, use a route file named with a dollar sign and a star: $*.tsx or $*.jsx. The $ indicates a dynamic segment, and the * means it matches any number of path segments.

This route catches all URLs that don't match other defined routes.

tsx
app/routes/$*.tsx

import { json } from '@remix-run/node';
import { useParams } from '@remix-run/react';

export const loader = async ({ params }) => {
  return json({ path: params['*'] });
};

export default function CatchAll() {
  const params = useParams();
  return <div>Catch all route matched: {params['*']}</div>;
}
๐Ÿ’ป

Example

This example shows a catch all route that displays the unmatched path segments. It uses useParams() to get the wildcard parameter and renders it.

tsx
app/routes/$*.tsx

import { json } from '@remix-run/node';
import { useParams } from '@remix-run/react';

export const loader = async ({ params }) => {
  return json({ path: params['*'] });
};

export default function CatchAll() {
  const params = useParams();
  return <div>Catch all route matched: {params['*']}</div>;
}
Output
If you visit /anything/here, the page shows: "Catch all route matched: anything/here"
โš ๏ธ

Common Pitfalls

  • Not using the $* syntax exactly; missing the star means only one segment is matched.
  • Placing the catch all route above more specific routes can cause it to match too early.
  • Forgetting to access the wildcard param with params['*'] instead of params.*.
tsx
/* Wrong: matches only one segment */
// app/routes/$slug.tsx

/* Right: matches all segments */
// app/routes/$*.tsx
๐Ÿ“Š

Quick Reference

PatternMeaningExample URL Match
$slug.tsxMatches one dynamic segment/post, /about
$*.tsxCatch all route matching all segments/anything/here, /foo/bar/baz
index.tsxMatches root or exact path/
โœ…

Key Takeaways

Use a route file named $*.tsx to create a catch all route in Remix.
The wildcard param is accessed with params['*'] inside loaders and components.
Catch all routes match any unmatched path segments as a fallback.
Place catch all routes after specific routes to avoid overriding them.
Catch all routes are useful for 404 pages or dynamic nested paths.