Chuyển đến nội dung

Bài 7 · Routes and Nested Layouts

Dynamic Segments, Optional Segments and Splat Routes

Learn dynamic URL params, optional segments, splat routes and 404 catch-all routes in React Router v7 framework mode, and how to validate params safely, with runnable stand-ins.

Most real sites have URLs that contain data: /products/42, /blog/hello-remix, /docs/guides/setup/install. You cannot write one route per product, so you describe the shape of the URL with a pattern, and the router hands the variable parts to your code as params. This lesson covers dynamic segments (:id), optional segments (:lang?), splats (*) and the catch-all 404 route, plus how to treat params as untrusted input.

Dynamic segments

A segment starting with : matches any single piece of the path (never one containing a slash).

TypeScript
// app/routes.ts (real, read-only)
route("products/:productId", "routes/product.tsx"),
route("teams/:teamId/members/:memberId", "routes/member.tsx"),

Your loader and component receive the values by name:

TSX
// app/routes/product.tsx (real, read-only)
import type { Route } from "./+types/product";

export async function loader({ params }: Route.LoaderArgs) {
  // params.productId is a string, typed from the route pattern
  const product = await getProduct(params.productId);
  return { product };
}

export default function Product({ loaderData, params }: Route.ComponentProps) {
  return <h1>{loaderData.product.name} (#{params.productId})</h1>;
}

The generated types read the pattern, so params.productId exists and params.nope is a compile error. Params are always strings and are already URL-decoded (/tags/c%2B%2B gives "c++").

Stand-in: a pattern matcher with params

This stand-in matches URL paths against patterns and returns the params, like the router does internally. Try changing the patterns or the URLs.

JS Stand-in: extract params from a URL

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

No output.

The second line returns null because dynamic segments never swallow a slash, which is also why /docs with an empty splat matches { "*": "" }.

Optional segments

Put a ? after a segment to make it optional. A single route then serves both /docs and /en/docs:

TypeScript
route(":lang?/docs", "routes/docs.tsx"),
route("categories/:category?", "routes/categories.tsx"),

In the loader, params.lang is string | undefined. Optional static segments work the same way (route("users/me?", ...)), but do not overdo it: a URL space that accepts many shapes is harder to reason about.

Splat routes

A trailing * matches the rest of the path, slashes included. The matched text lands in params["*"].

TSX
// route("files/*", "routes/files.tsx")  (real, read-only)
export async function loader({ params }: Route.LoaderArgs) {
  const path = params["*"]; // "photos/2025/trip.jpg" for /files/photos/2025/trip.jpg
  return { path, parts: path.split("/") };
}

Splats are right for file browsers, wiki-style pages, and docs trees whose depth you do not control.

The catch-all 404 route

A route with the path * at the end of the config matches everything else. Use it to render a branded "Page not found" page. Remember to set the HTTP status, otherwise search engines see a 200 for a page that does not exist (a "soft 404").

TSX
// route("*", "routes/not-found.tsx")  (real, read-only)
import { data } from "react-router";

export function loader() {
  throw data("Not Found", { status: 404 });
}

export default function NotFound() {
  return <h1>Page not found</h1>; // not rendered; the ErrorBoundary shows below
}

export function ErrorBoundary() {
  return <h1>Page not found</h1>;
}

Throwing data(..., { status: 404 }) sends a real 404 and renders the nearest error boundary. Throwing responses and 404s covers this in the error-handling chapter. When no route at all matches, the root error boundary shows a 404 automatically, so a catch-all route is mostly for a nicer, layout-aware page.

Specificity and conflicts

Given /products/new, /products/:id and /products/*, the static pattern wins, then the param, then the splat. See the previous lesson for the ranking stand-in.

Treat params as untrusted input

Anyone can type any URL. A param is just text that arrived from the network.

  • Convert and check: Number(params.id) can be NaN; Number.isInteger is not enough on its own if you need positive IDs.
  • Do not build file paths or SQL from params directly. Use parameterised queries and reject .. in file names.
  • Respond with a 404 when nothing matches or when the value is malformed, not a crash.
JS Stand-in: validate a param and answer 404 or 400

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

No output.

A malformed value gets 400, a well-formed value that does not exist gets 404, and only a real record gets a body. That distinction helps clients, logs and crawlers.

Linking to dynamic routes

Build links with the same pieces. Encode any user-provided value:

TSX
<Link to={`/tags/${encodeURIComponent(tag)}`}>{tag}</Link>
<Link to={{ pathname: "/products", search: "?sort=price" }}>Cheapest</Link>

Forgetting encodeURIComponent breaks tags like c++, a/b or 50%.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What is the type of params.productId for the route products/:productId?

    Params are always strings, already URL-decoded. Convert and validate them yourself.
  2. 2. Where does a splat route put the matched rest of the path?

    The star segment is available as params['*'] and can contain slashes.
  3. 3. What does route(':lang?/docs', ...) match?

    The question mark makes the first segment optional, so params.lang may be undefined.
  4. 4. Why should a catch-all 404 page send a 404 status?

    A friendly page with status 200 is a soft 404 that crawlers may index. Throw data(..., { status: 404 }).

Summary

  • :name matches one segment, :name? makes it optional, * matches the rest of the path into params["*"].
  • Params are strings; validate and convert them, and respond with 400 or 404 for bad input.
  • Static beats dynamic beats splat; a final * route can render a custom not-found page.
  • Encode user text when building links.

Next: The Flat Routes Convention

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.