File-Based Routing Conventions
While React Router v7 recommends manual route configuration, the@react-router/fs-routes package provides file-based routing conventions for those who prefer convention over configuration.
Setup
Install the package:flatRoutes() in your routes.ts:
app/routes/ directory.
Basic File Naming
Simple Routes
File names map directly to URL paths:Nested Routes with Dot Notation
Use dots (.) to create nested routes:
dashboard.tsx) must render an <Outlet /> for children.
Dynamic Segments
Prefix segments with$ to create dynamic parameters:
Index Routes
Use_index suffix for index routes:
Layout Routes (Pathless)
Prefix with_ to create layout routes that don’t add URL segments:
_marketing.tsx and _app.tsx are layout routes that wrap their children without adding URL segments.
Folder-Based Routes
Alternatively, use folders withroute.tsx or index.tsx:
route.tsx and file name in the same folder:
Escaping Special Characters
Use square brackets[] to escape special characters:
Optional Segments
Wrap segments in parentheses() to make them optional:
Splat Routes (Catch-All)
Use$ alone to match remaining path segments:
params["*"]:
Escaping Routes (Opt-Out of Nesting)
Use trailing underscore_ to escape parent layout:
Combining Conventions
Mix file and folder approaches:Ignored Files
Files matching these patterns are ignored:.DS_Store- Any file starting with
.(hidden files) - Files matching patterns in the
ignoredRouteFilesconfig
Custom Routes Directory
Change the routes directory:Route Conflicts
React Router detects and warns about route conflicts:users.new.tsx should be defined before users.$id.tsx to match /users/new correctly. React Router automatically handles this when using flatRoutes().
Complete Example
A real-world file structure:Migration Strategy
When migrating from manual config to file-based routing:- Start with existing
routes.tsmanual configuration - Gradually move routes to file-based conventions
- Mix both approaches during migration:
Best Practices
- Consistent structure: Choose file or folder approach and stick with it
- Descriptive names: Use clear, semantic file names
- Logical grouping: Group related routes in folders
- Avoid deep nesting: Keep route hierarchies shallow (3-4 levels max)
- Use layouts wisely: Leverage pathless layouts (
_) for shared UI - Document escapes: Comment why you’re using
_escapes - Consider manual config: For complex apps, manual configuration may be clearer
When to Use File-Based Routing
Good for:- Simple applications
- Rapid prototyping
- Teams familiar with file-based conventions
- Projects with standard routing patterns
- Complex routing logic
- Routes determined at runtime
- Heavy route code splitting
- Team prefers explicit configuration
- Multiple routes share the same component