Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 50 ยท Framework Mode

Route Config and File Routes

Describe framework-mode routes in routes.ts with route(), index(), layout() and prefix(), or derive them from file names with flatRoutes, and use generated types.

In data mode your routes were objects in your own code. In framework mode they live in one file, app/routes.ts, and every entry points to a file: the route module that holds that page's component, loader, action and metadata. The framework reads the config, builds the nested route tree, splits one bundle chunk per module and generates TypeScript types for each of them.

You have two ways to write that config. You can list routes explicitly with a handful of helper functions, which is the default and the most readable choice. Or you can let the file names in a folder describe the URLs, the style popularized by Remix and Next.js. This lesson covers both. It follows Framework Mode Overview, so the code is read-only, and the live examples are small stand-ins that run the same logic in your browser.

The route config

routes.ts default-exports an array. Four helpers from @react-router/dev/routes build its entries:

  • route(path, file, children?) is a URL segment (or several) that renders a module.
  • index(file) is the default child of its parent: it renders at the parent's own URL.
  • layout(file, children) renders a module around its children without adding a URL segment, like a pathless layout route (see Layout Routes and Pathless Routes).
  • prefix(path, routes) adds a path in front of several routes, without needing a module of its own.
TypeScript
// app/routes.ts (read-only)
import { type RouteConfig, route, index, layout, prefix } from '@react-router/dev/routes';

export default [
  index('routes/home.tsx'),
  route('about', 'routes/about.tsx'),

  layout('layouts/auth.tsx', [
    route('login', 'routes/login.tsx'),
    route('register', 'routes/register.tsx'),
  ]),

  ...prefix('projects', [
    index('routes/projects/index.tsx'),
    layout('routes/projects/layout.tsx', [
      route(':pid', 'routes/projects/project.tsx'),
      route(':pid/edit', 'routes/projects/edit.tsx'),
    ]),
  ]),

  route('files/*', 'routes/files.tsx'),
  route('*', 'routes/not-found.tsx'),
] satisfies RouteConfig;

A few facts that save time:

  • Paths to files are relative to the app directory (the folder that holds routes.ts), so 'routes/home.tsx' means app/routes/home.tsx. You are free to organize folders however you like; there is no required routes folder when you use explicit config.
  • Every route is nested inside root.tsx. The root route is implicit, so it never appears in routes.ts.
  • prefix returns an array, which is why it is spread with .... It adds the path to routes that have one and to index routes, and it looks inside pathless layouts, so the layout itself stays pathless.
  • Segments use the same syntax you already know: :pid is a dynamic segment, :lang? makes a segment optional and a trailing * is a splat that matches the rest of the URL. See Dynamic Segments and useParams.
  • A route can take an options object, for example route('teams/:teamId', 'routes/team.tsx', { id: 'team', caseSensitive: true }, [ /* children */ ]). Use id when you need a stable route id for useRouteLoaderData.
flowchart TD
    R["root.tsx<br/>implicit parent of everything"] --> H["index: routes/home.tsx<br/>/"]
    R --> A["route about: routes/about.tsx<br/>/about"]
    R --> L1["layout: layouts/auth.tsx<br/>no URL segment"]
    L1 --> LG["login: /login"]
    L1 --> RG["register: /register"]
    R --> L2["layout: routes/projects/layout.tsx<br/>no URL segment"]
    L2 --> PP["projects/:pid"]
    L2 --> PE["projects/:pid/edit"]

The config array becomes a tree. Layouts add components to the tree, not segments to the URL.

Real library or stand-in? The code above is the real framework-mode API. The live examples below use small hand-written stand-ins: the first re-implements route(), index(), layout() and prefix() in plain JavaScript and then matches a URL against the resulting tree; the second is a converter for the flatRoutes file-name convention. They follow the documented rules, but they are not the real build, and the stand-in matcher uses the first matching entry, whereas the real router ranks by specificity. The * entry is last, as in the config above.

Click the links to see which modules would render for each URL, outermost first.

Build a route tree with route(), layout() and prefix()

Look at /projects/7/edit: the chain is root.tsx, the projects layout and edit.tsx, and the layout contributed no URL segment. In the printed tree you can also see what prefix('projects', ...) did: the index entry became /projects, and the two routes inside the layout became projects/:pid and projects/:pid/edit, while the layout stayed without a path.

Route modules and generated types

Each file in the config is a route module. Its default export is the component, and named exports configure the route. The most common are loader, action, meta, links, headers, handle (see Route Handles and Breadcrumbs), ErrorBoundary and the client-side variants clientLoader and clientAction. The next two lessons explain what they do.

Because the framework knows both the config and the module, it can generate a types file for every route. For routes/projects/project.tsx with the path projects/:pid, you import types from a sibling +types path:

TSX
// app/routes/projects/project.tsx (read-only)
import type { Route } from './+types/project';

export async function loader({ params }: Route.LoaderArgs) {
  // params.pid is typed as string
  return { project: await getProject(params.pid) };
}

export default function Project({ loaderData, params }: Route.ComponentProps) {
  // loaderData is typed from the return value of loader
  return <h1>{loaderData.project.name}</h1>;
}

There is no +types folder in your source tree. The react-router typegen command (run automatically by react-router dev, and by the typecheck script) writes the files into a hidden .react-router/types directory, and your tsconfig.json merges that directory with rootDirs, so ./+types/project resolves as if it were a neighbor. What you get:

  • Typed params. :pid becomes string, an optional :lang? becomes string | undefined, and a splat is available as params['*'].
  • Typed data. loaderData and actionData are inferred from what your loader and action return, so there is no more casting after useLoaderData.
  • Type-safe props. The component receives loaderData, actionData, params and matches as props, so many routes need no hooks at all.
flowchart LR
    A["routes.ts<br/>paths and files"] --> B["react-router typegen"]
    C["Route module<br/>loader, action, component"] --> B
    B --> D[".react-router/types<br/>+types/project"]
    D --> E["import type { Route }<br/>typed params, loaderData, props"]

The generated types combine the path from routes.ts with the exports of the module.

Generated files are build output. Keep .react-router/ in .gitignore, and let the dev server or the typecheck script recreate it.

Config as code

routes.ts is a normal TypeScript module, so the array can be computed: loop over a list of locales, read a folder, or fetch a table from a CMS (the config may be asynchronous). This is useful when the shape of your URLs comes from data rather than from a person typing. Only the final array matters; the framework does not care how you built it.

TypeScript
// app/routes.ts (read-only)
import { type RouteConfig, route } from '@react-router/dev/routes';

const docs = ['intro', 'install', 'deploy'];

export default [
  ...docs.map((slug) => route(`docs/${slug}`, 'routes/doc.tsx', { id: `doc-${slug}` })),
] satisfies RouteConfig;

Giving each entry its own id is required when the same file appears more than once, because ids must be unique.

File-based routes with flatRoutes

If you prefer file names to describe URLs, a helper package turns a folder into a route config. Install @react-router/fs-routes and return its result from routes.ts:

TypeScript
// app/routes.ts (read-only)
import { type RouteConfig } from '@react-router/dev/routes';
import { flatRoutes } from '@react-router/fs-routes';

export default flatRoutes() satisfies RouteConfig;

By default it reads app/routes/, and each file there becomes a route. The name uses dots instead of slashes, and the dots also express nesting: a file named concerts.tsx is the layout for every file starting with concerts.. The conventions:

File name URL Meaning
_index.tsx / Index route of its parent (here the root)
about.tsx /about A plain route
concerts.tsx /concerts Layout for the concerts.* files; renders an Outlet
concerts._index.tsx /concerts Index inside the concerts layout
concerts.$city.tsx /concerts/:city $ makes a dynamic segment
concerts_.mine.tsx /concerts/mine Trailing _ opts out of nesting inside concerts.tsx
_auth.tsx none Leading _ makes a pathless layout
_auth.login.tsx /login A route inside the pathless layout
($lang).pricing.tsx /:lang?/pricing Parentheses make a segment optional
files.$.tsx /files/* A lone $ is a splat

A route can also be a folder containing a route.tsx, which lets you keep helper files next to it. To use a literal dot in a URL, wrap it in square brackets (sitemap[.]xml.tsx). You can combine the two styles by spreading flatRoutes() after explicit entries, and options such as ignoredRouteFiles and rootDirectory change what is read. Apps migrating from Remix can use the adapter package @react-router/remix-routes-option-adapter, which accepts Remix-style route definitions.

Edit the list of file names below (one per line) and watch the table follow. This is a stand-in for the naming rules above, not the real flatRoutes.

From file names to URLs

Compare concerts.trending with concerts_.mine: both start with concerts, but the first renders inside the concerts layout, while the second (with the trailing underscore) renders directly in the root, and its URL is still /concerts/mine. Delete the concerts.tsx line and concerts.trending loses its parent, because nesting only happens when the parent file exists.

Which style should you choose?

Explicit routes.ts flatRoutes()
The URL structure is visible in one file The URL structure is hidden in file names
Folders are yours to organize The routes/ folder shape is dictated by names
Renaming a URL means editing the config Renaming a URL means renaming a file
Easy to compute or generate Harder to generate, easy to scan in an editor

Neither is "more advanced". Explicit config is a good default for teams, because a search for a URL finds it in one place. File routes suit people who like a convention-over-configuration workflow, and nothing stops you from mixing them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In routes.ts, what does layout('layouts/auth.tsx', [route('login', 'routes/login.tsx')]) do?

    layout() adds a component to the tree, not a segment to the URL. The child keeps its own path, so the page is still /login.
  2. 2. Where are the file paths in route('about', 'routes/about.tsx') resolved from?

    Paths are relative to the app directory, so this points to app/routes/about.tsx.
  3. 3. What does prefix('projects', [index('a.tsx'), route(':pid', 'b.tsx')]) produce?

    prefix puts the path in front of every route that has one, and index routes become the prefix itself. It returns an array, so you spread it into the config.
  4. 4. With flatRoutes, which file name gives the URL /concerts/mine but does NOT render inside the concerts.tsx layout?

    A trailing underscore on a segment opts out of layout nesting but keeps that segment in the URL. A leading underscore creates a pathless layout, and $ makes a dynamic segment.
  5. 5. Where do the types imported from './+types/project' come from?

    Typegen combines the path in routes.ts with the exports of the route module and writes types into a hidden directory that tsconfig merges through rootDirs.

Summary

  • app/routes.ts default-exports an array built with route(), index(), layout() and prefix(); every entry points to a route module relative to the app directory.
  • layout() and pathless nesting add components without URL segments; prefix() returns an array and adds a path in front of its routes.
  • All routes render inside the implicit root route, root.tsx.
  • A route module exports a component plus loader, action, meta, links and more; react-router typegen generates Route types with typed params and loader data.
  • The config is ordinary code, so it can be computed; give repeated modules unique id options.
  • flatRoutes() derives routes from file names: dots nest or separate segments, $ is dynamic or a splat, a leading _ is pathless, a trailing _ opts out of nesting.

Next: Server Loaders, Client Loaders and Actions