0
0
RemixHow-ToBeginner ยท 3 min read

How to Use Splat Route in Remix for Dynamic Paths

In Remix, use a splat route by naming a route file with $ followed by *.tsx (e.g., $*.tsx) to capture all remaining path segments as a single parameter. This lets you handle dynamic nested paths easily by accessing the splat parameter in your loader or component.
๐Ÿ“

Syntax

A splat route in Remix uses a special file name pattern to catch multiple path segments as one parameter. The syntax is to prefix the file name with $ and use an asterisk * to indicate a splat.

  • $*.tsx or $*.jsx: Matches all remaining path segments as a single string.
  • The splat parameter is accessible via params["*"] in loaders or components.
typescript
app/routes/$*.tsx

// This route matches /anything/here/and/more
// The splat param contains 'anything/here/and/more'
๐Ÿ’ป

Example

This example shows a Remix route file named $*.tsx that captures all path segments after the base URL and displays them.

typescript
import { useLoaderData } from "@remix-run/react";
import type { LoaderFunction } from "@remix-run/node";

export const loader: LoaderFunction = async ({ params }) => {
  // params["*"] contains the splat path as a string
  return { splat: params["*"] || "" };
};

export default function SplatRoute() {
  const data = useLoaderData<typeof loader>();
  return (
    <main>
      <h1>Splat Route</h1>
      <p>You visited: <strong>{data.splat || "(root)"}</strong></p>
    </main>
  );
}
Output
<h1>Splat Route</h1> <p>You visited: anything/here/and/more</p>
โš ๏ธ

Common Pitfalls

  • Not using $*.tsx but just $slug.tsx captures only one segment, not multiple.
  • Accessing the splat parameter incorrectly; it must be params["*"], not params.splat.
  • Forgetting that the splat param is a string with slashes, so you may need to split it if you want individual segments.
typescript
/* Wrong: captures only one segment */
// app/routes/$slug.tsx

/* Right: captures all remaining segments */
// app/routes/$*.tsx

// Access splat param correctly
const splat = params["*"];
๐Ÿ“Š

Quick Reference

PatternMatchesParam Access
$slug.tsxOne dynamic segment (e.g. /post)params.slug
$*.tsxAll remaining segments (e.g. /a/b/c)params["*"]
โœ…

Key Takeaways

Use the file name pattern $*.tsx to create a splat route that matches multiple path segments.
Access the splat parameter with params["*"] in loaders and components.
Splat routes capture the rest of the URL path as a single string with slashes.
Use splat routes to handle deeply nested or unknown path depths easily.
Remember that $slug.tsx captures only one segment, while $*.tsx captures many.