Path Parameters with Type Safety
You'll learn how to define and access route parameters in TanStack Router with automatic TypeScript inference, catching errors before runtime.
The Problem with Traditional Routers
In most routers, path parameters are just strings extracted from the URL. You write /users/:id, then hope you spelled it right when accessing params.id. No compiler help, no autocomplete, just runtime surprises.
TanStack Router changes this completely.
Type-Safe Path Parameters
When you define a route with parameters, TanStack Router infers their names and types automatically:
import { createRoute } from '@tanstack/react-router';
import { rootRoute } from './root';
const userRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/users/$userId', // $ denotes a parameter
component: UserPage,
});
function UserPage() {
const { userId } = userRoute.useParams();
// userId is typed as string automatically
// Autocomplete works! Typos caught at compile time!
return <div>User ID: {userId}</div>;
}
The magic is in the $ prefix — it tells TanStack Router "this is a parameter named userId". TypeScript then knows that useParams() will return an object with a userId property.
Adding Validation
For even stronger safety, use the params validator option with a schema library (covered in future lessons):
const productRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/products/$productId',
// params validator will be covered next
});
Key Takeaway: TanStack Router's $paramName syntax and useParams() hook provide full TypeScript inference for path parameters, eliminating an entire class of typo-based bugs and giving you autocomplete everywhere you access route data.