원클릭으로
tanstak-touter
Guide for using TanStack Router library. Use when working with React projects that need routing functionality.
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
메뉴
Guide for using TanStack Router library. Use when working with React projects that need routing functionality.
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
SOC 직업 분류 기준
Usarla para probar la aplicación e2e con Playwright MCP o CLI. MANTENER ACTUALIZADA con instrucciones que ahorren tiempo y eviten snapshots repetitivos y agregar nuevo coocimiento cuando navegues a nuevas secciones de la aplicación.
Guide for using @galiprandi/react-tools library. Use when working with React projects that need lightweight, dependency-free utilities including components (AsyncBlock, Form, Input, DateTime, Dialog, Observer, LazyRender) and hooks (useAI, useAISummarize, useLanguageDetection, useTranslator, useAIPrompt, useAIWrite, useAIRewriter, useAIProofreader, useDebounce, useTimer, useList). This library provides accessible, composable React utilities with no configuration needed.
| name | tanstak-touter |
| description | Guide for using TanStack Router library. Use when working with React projects that need routing functionality. |
<@tanstack/react-router_api> Always Apply: false - This rule should only be applied when relevant files are open Always apply this rule in these files: src//*.ts, src//*.tsx
The ActiveLinkOptions type extends the LinkOptions type and contains additional options that can be used to describe how a link should be styled when it is active.
type ActiveLinkOptions = LinkOptions & {
activeProps?:
| React.AnchorHTMLAttributes<HTMLAnchorElement>
| (() => React.AnchorHTMLAttributes<HTMLAnchorElement>)
inactiveProps?:
| React.AnchorHTMLAttributes<HTMLAnchorElement>
| (() => React.AnchorHTMLAttributes<HTMLAnchorElement>)
}
The ActiveLinkOptions object accepts/contains the following properties:
activePropsReact.AnchorHTMLAttributes<HTMLAnchorElement>inactivePropsReact.AnchorHTMLAttributes<HTMLAnchorElement>The AsyncRouteComponent type is used to describe a code-split route component that can be preloaded using a component.preload() method.
type AsyncRouteComponent<TProps> = SyncRouteComponent<TProps> & {
preload?: () => Promise<void>
}
[!CAUTION] This class has been deprecated and will be removed in the next major version of TanStack Router. Please use the
createFileRoutefunction instead.
The FileRoute class is a factory that can be used to create a file-based route instance. This route instance can then be used to automatically generate a route tree with the tsr generate and tsr watch commands.
FileRoute constructorThe FileRoute constructor accepts a single argument: the path of the file that the route will be generated for.
string literaltsr generate and tsr watch commands.FileRoute class that can be used to create a route.FileRoute methodsThe FileRoute class implements the following method(s):
.createRoute methodThe createRoute method is a method that can be used to configure the file route instance. It accepts a single argument: the options that will be used to configure the file route instance.
Omit<RouteOptions, 'getParentRoute' | 'path' | 'id'>RouteOptionsRoute class, but with the getParentRoute, path, and id options omitted since they are unnecessary for file-based routing.A Route instance that can be used to configure the route to be inserted into the route-tree.
⚠️ Note: For
tsr generateandtsr watchto work properly, the file route instance must be exported from the file using theRouteidentifier.
import { FileRoute } from '@tanstack/react-router'
export const Route = new FileRoute('/').createRoute({
loader: () => {
return 'Hello World'
},
component: IndexComponent,
})
function IndexComponent() {
const data = Route.useLoaderData()
return <div>{data}</div>
}
The LinkOptions type extends the NavigateOptions type and contains additional options that can be used by TanStack Router when handling actual anchor element attributes.
type LinkOptions = NavigateOptions & {
target?: HTMLAnchorElement['target']
activeOptions?: ActiveOptions
preload?: false | 'intent'
preloadDelay?: number
disabled?: boolean
}
The LinkOptions object accepts/contains the following properties:
targetHTMLAnchorElement['target']activeOptionsActiveOptionspreloadfalse | 'intent' | 'viewport' | 'render'preloadDelaynumberdisabledbooleanThe LinkProps type extends the ActiveLinkOptions and React.AnchorHTMLAttributes<HTMLAnchorElement> types and contains additional props specific to the Link component.
type LinkProps = ActiveLinkOptions &
Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'children'> & {
children?:
| React.ReactNode
| ((state: { isActive: boolean }) => React.ReactNode)
}
ActiveLinkOptionsReact.AnchorHTMLAttributes<HTMLAnchorElement>childrenReact.ReactNode | ((state: { isActive: boolean }) => React.ReactNode)isActive boolean value that can be used to determine if the link is active.The MatchRouteOptions type is used to describe the options that can be used when matching a route.
interface MatchRouteOptions {
pending?: boolean
caseSensitive?: boolean /* @deprecated */
includeSearch?: boolean
fuzzy?: boolean
}
The MatchRouteOptions type has the following properties:
pending propertybooleantrue, will match against pending location instead of the current locationcaseSensitivebooleantrue, will match against the current location with case sensitivitycaseSensitive option on the routerincludeSearch propertybooleantrue, will match against the current location's search params using a deep inclusive check. e.g. { a: 1 } will match for a current location of { a: 1, b: 2 }fuzzy propertybooleantrue, will match against the current location using a fuzzy match. e.g. /posts will match for a current location of /posts/123The NavigateOptions type is used to describe the options that can be used when describing a navigation action in TanStack Router.
type NavigateOptions = ToOptions & {
replace?: boolean
resetScroll?: boolean
hashScrollIntoView?: boolean | ScrollIntoViewOptions
viewTransition?: boolean | ViewTransitionOptions
ignoreBlocker?: boolean
reloadDocument?: boolean
href?: string
}
The NavigateOptions object accepts the following properties:
replacebooleanfalse.true, the location will be committed to the browser history using history.replace instead of history.push.resetScrollbooleantrue so that the scroll position will be reset to 0,0 after the location is committed to the browser history.false, the scroll position will not be reset to 0,0 after the location is committed to history.hashScrollIntoViewboolean | ScrollIntoViewOptionstrue so the element with an id matching the hash will be scrolled into view after the location is committed to history.false, the element with an id matching the hash will not be scrolled into view after the location is committed to history.scrollIntoView method as options.ScrollIntoViewOptions.viewTransitionboolean | ViewTransitionOptionsfalse.true, navigation will be called using document.startViewTransition().ViewTransitionOptions, route navigations will be called using document.startViewTransition({update, types}) where types will determine the strings array passed with ViewTransitionOptions["types"]. If the browser does not support viewTransition types, the navigation will fall back to normal document.startTransition(), same as if true was passed.ignoreBlockerbooleanfalse.true, navigation will ignore any blockers that might prevent it.reloadDocumentbooleanfalse.true, navigation to a route inside of router will trigger a full page load instead of the traditional SPA navigation.hrefType: string
Optional
This can be used instead of to to navigate to a fully built href, e.g. pointing to an external target.
The NotFoundError type is used to represent a not-found error in TanStack Router.
export type NotFoundError = {
global?: boolean
data?: any
throw?: boolean
routeId?: string
headers?: HeadersInit
}
The NotFoundError object accepts/contains the following properties:
global property (⚠️ deprecated, use routeId: rootRouteId instead)booleandefault: falsenotFoundComponent of the root route instead of bubbling up from the route that threw it. This has the same behavior as importing the root route and calling RootRoute.notFound().data propertyanynotFoundComponent when the not-found error is handledthrow propertybooleandefault: falsethrowing in a function might cause it to have a return type of never. In that case, you can use notFound({ throw: true }) to throw the not-found object instead of returning it.routeId propertystringnotFoundComponent, the error will bubble up to the parent route (and be handled by the root route if necessary). By default, TanStack Router will attempt to handle the not-found error with the route that threw it.headers propertyHeadersInit[!CAUTION] This class has been deprecated and will be removed in the next major version of TanStack Router. Please use the
notFoundComponentroute option that is present during route configuration. See the Not Found Errors guide for more information.
The NotFoundRoute class extends the Route class and can be used to create a not found route instance. A not found route instance can be passed to the routerOptions.notFoundRoute option to configure a default not-found/404 route for every branch of the route tree.
The NotFoundRoute constructor accepts an object as its only argument.
Omit<
RouteOptions,
| 'path'
| 'id'
| 'getParentRoute'
| 'caseSensitive'
| 'parseParams'
| 'stringifyParams'
>
import { NotFoundRoute, createRouter } from '@tanstack/react-router'
import { Route as rootRoute } from './routes/__root'
import { routeTree } from './routeTree.gen'
const notFoundRoute = new NotFoundRoute({
getParentRoute: () => rootRoute,
component: () => <div>Not found!!!</div>,
})
const router = createRouter({
routeTree,
notFoundRoute,
})
// ... other code
The ParsedHistoryState type represents a parsed state object. Additionally to HistoryState, it contains the index and the unique key of the route.
export type ParsedHistoryState = HistoryState & {
key?: string // TODO: Remove in v2 - use __TSR_key instead
__TSR_key?: string
__TSR_index: number
}
The ParsedLocation type represents a parsed location in TanStack Router. It contains a lot of useful information about the current location, including the pathname, search params, hash, location state, and route masking information.
interface ParsedLocation {
href: string
pathname: string
search: TFullSearchSchema
searchStr: string
state: ParsedHistoryState
hash: string
maskedLocation?: ParsedLocation
unmaskOnReload?: boolean
}
The Redirect type is used to represent a redirect action in TanStack Router.
export type Redirect = {
statusCode?: number
throw?: any
headers?: HeadersInit
} & NavigateOptions
The Redirect object accepts/contains the following properties:
statusCode propertynumberthrow propertyanythrowing in a function might cause it to have a return type of never. In that case, you can use redirect({ throw: true }) to throw the redirect object instead of returning it.headers propertyHeadersInitSince Redirect extends NavigateOptions, it also supports navigation properties:
to: Use for internal application routes (e.g., /dashboard, ../profile)href: Use for external URLs (e.g., https://example.com, https://authprovider.com)Important: For external URLs, always use the
hrefproperty instead ofto. Thetoproperty is designed for internal navigation within your application.
This type is used to register a route tree with a router instance. Doing so unlocks the full type safety of TanStack Router, including top-level exports from the @tanstack/react-router package.
export type Register = {
// router: [Your router type here]
}
To register a route tree with a router instance, use declaration merging to add the type of your router instance to the Register interface under the router property:
const router = createRouter({
// ...
})
declare module '@tanstack/react-router' {
interface Register {
router: typeof router
}
}
[!CAUTION] This class has been deprecated and will be removed in the next major version of TanStack Router. Please use the
createRootRoutefunction instead.
The RootRoute class extends the Route class and can be used to create a root route instance. A root route instance can then be used to create a route tree.
RootRoute constructorThe RootRoute constructor accepts an object as its only argument.
The options that will be used to configure the root route instance.
Omit<
RouteOptions,
| 'path'
| 'id'
| 'getParentRoute'
| 'caseSensitive'
| 'parseParams'
| 'stringifyParams'
>
RouteOptionsA new Route instance.
import { RootRoute, createRouter, Outlet } from '@tanstack/react-router'
const rootRoute = new RootRoute({
component: () => <Outlet />,
// ... root route options
})
const routeTree = rootRoute.addChildren([
// ... other routes
])
const router = createRouter({
routeTree,
})
[!CAUTION] This class has been deprecated and will be removed in the next major version of TanStack Router. Please use the
getRouteApifunction instead.
The RouteApi class provides type-safe version of common hooks like useParams, useSearch, useRouteContext, useNavigate, useLoaderData, and useLoaderDeps that are pre-bound to a specific route ID and corresponding registered route types.
The RouteApi constructor accepts a single argument: the options that will be used to configure the RouteApi instance.
opts.routeId optionstringRouteApi instance will be boundRouteApi that is pre-bound to the route ID that it was called with.import { RouteApi } from '@tanstack/react-router'
const routeApi = new RouteApi({ id: '/posts' })
export function PostsPage() {
const posts = routeApi.useLoaderData()
// ...
}
The RouteApi describes an instance that provides type-safe versions of common hooks like useParams, useSearch, useRouteContext, useNavigate, useLoaderData, and useLoaderDeps that are pre-bound to a specific route ID and corresponding registered route types.
RouteApi properties and methodsThe RouteApi has the following properties and methods:
useMatch method useMatch<TSelected = TAllContext>(opts?: {
select?: (match: TAllContext) => TSelected
}): TSelected
useMatch hook that is pre-bound to the route ID that the RouteApi instance was created with.opts.select
(match: RouteMatch) => TSelecteduseMatch. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.opts.structuralSharing
booleanselect.select function is provided, the return value of the select function.select function is provided, the RouteMatch object or a loosened version of the RouteMatch object if opts.strict is false.useRouteContext method useRouteContext<TSelected = TAllContext>(opts?: {
select?: (search: TAllContext) => TSelected
}): TSelected
useRouteContext hook that is pre-bound to the route ID that the RouteApi instance was created with.opts.select
(match: RouteContext) => TSelecteduseRouteContext. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.select function is provided, the return value of the select function.select function is provided, the RouteContext object or a loosened version of the RouteContext object if opts.strict is false.useSearch method useSearch<TSelected = TFullSearchSchema>(opts?: {
select?: (search: TFullSearchSchema) => TSelected
}): TSelected
useSearch hook that is pre-bound to the route ID that the RouteApi instance was created with.opts.select
(match: TFullSearchSchema) => TSelecteduseSearch. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.opts.structuralSharing
booleanselect.select function is provided, the return value of the select function.select function is provided, the TFullSearchSchema object or a loosened version of the TFullSearchSchema object if opts.strict is false.useParams method useParams<TSelected = TAllParams>(opts?: {
select?: (params: TAllParams) => TSelected
}): TSelected
useParams hook that is pre-bound to the route ID that the RouteApi instance was created with.opts.select
(match: TAllParams) => TSelecteduseParams. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.opts.structuralSharing
booleanselect.select function is provided, the return value of the select function.select function is provided, the TAllParams object or a loosened version of the TAllParams object if opts.strict is false.useLoaderData method useLoaderData<TSelected = TLoaderData>(opts?: {
select?: (search: TLoaderData) => TSelected
}): TSelected
useLoaderData hook that is pre-bound to the route ID that the RouteApi instance was created with.opts.select
(match: TLoaderData) => TSelecteduseLoaderData. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.opts.structuralSharing
booleanselect.select function is provided, the return value of the select function.select function is provided, the TLoaderData object or a loosened version of the TLoaderData object if opts.strict is false.useLoaderDeps method useLoaderDeps<TSelected = TLoaderDeps>(opts?: {
select?: (search: TLoaderDeps) => TSelected
}): TSelected
useLoaderDeps hook that is pre-bound to the route ID that the RouteApi instance was created with.opts.select
(match: TLoaderDeps) => TSelecteduseLoaderDeps.opts.structuralSharing
booleanselect.select function is provided, the return value of the select function.select function is provided, the TLoaderDeps object.useNavigate method useNavigate(): // navigate function
useNavigate that is pre-bound to the route ID that the RouteApi instance was created with.redirect method redirect(opts?: RedirectOptions): Redirect
redirect function that is pre-bound to the route ID that the RouteApi instance was created with.from parameter is automatically set to the route ID, enabling type-safe relative redirects.redirect except from, which is automatically provided.Redirect object that can be thrown from beforeLoad or loader callbacks.import { getRouteApi } from '@tanstack/react-router'
const routeApi = getRouteApi('/dashboard/settings')
export const Route = createFileRoute('/dashboard/settings')({
beforeLoad: ({ context }) => {
if (!context.user) {
// Type-safe redirect - 'from' is automatically '/dashboard/settings'
throw routeApi.redirect({
to: '../login', // Relative path to sibling route
})
}
},
})
[!CAUTION] This class has been deprecated and will be removed in the next major version of TanStack Router. Please use the
createRoutefunction instead.
The Route class implements the RouteApi class and can be used to create route instances. A route instance can then be used to create a route tree.
Route constructorThe Route constructor accepts an object as its only argument.
RouteOptionsA new Route instance.
import { Route } from '@tanstack/react-router'
import { rootRoute } from './__root'
const indexRoute = new Route({
getParentRoute: () => rootRoute,
path: '/',
loader: () => {
return 'Hello World'
},
component: IndexComponent,
})
function IndexComponent() {
const data = indexRoute.useLoaderData()
return <div>{data}</div>
}
The RouteMask type extends the ToOptions type and has other the necessary properties to create a route mask.
The RouteMask type accepts an object with the following properties:
...ToOptionsToOptionsoptions.routeTreeTRouteTreeoptions.unmaskOnReloadbooleantrue, the route mask will be removed when the page is reloadedThe RouteMatch type represents a route match in TanStack Router.
interface RouteMatch {
id: string
routeId: string
pathname: string
params: Route['allParams']
status: 'pending' | 'success' | 'error' | 'redirected' | 'notFound'
isFetching: false | 'beforeLoad' | 'loader'
showPending: boolean
error: unknown
paramsError: unknown
searchError: unknown
updatedAt: number
loaderData?: Route['loaderData']
context: Route['allContext']
search: Route['fullSearchSchema']
fetchedAt: number
abortController: AbortController
cause: 'enter' | 'stay'
ssr?: boolean | 'data-only'
}
The RouteOptions type is used to describe the options that can be used when creating a route.
The RouteOptions type accepts an object with the following properties:
getParentRoute method() => TParentRoutepath propertystringid is provided to configure the route as a pathless layout routeid propertystringpath is not providedcomponent propertyRouteComponent or LazyRouteComponent<Outlet />errorComponent propertyRouteComponent or LazyRouteComponentrouterOptions.defaultErrorComponentpendingComponent propertyRouteComponent or LazyRouteComponentrouterOptions.defaultPendingComponentnotFoundComponent propertyNotFoundRouteComponent or LazyRouteComponentrouterOptions.defaultNotFoundComponentvalidateSearch method(rawSearchParams: unknown) => TSearchSchemaSearchSchemaInput type like this: (searchParams: TSearchSchemaInput & SearchSchemaInput) => TSearchSchema. If this tag is present, TSearchSchemaInput will be used to type the search property of <Link /> and navigate() instead of TSearchSchema. The difference between TSearchSchemaInput and TSearchSchema can be useful, for example, to express optional search parameters.search.middlewares property(({search: TSearchSchema, next: (newSearch: TSearchSchema) => TSearchSchema}) => TSearchSchema)[]next.parseParams method (⚠️ deprecated, use params.parse instead)(rawParams: Record<string, string>) => TParamsstringifyParams method (⚠️ deprecated, use params.stringify instead)(params: TParams) => Record<string, string>parseParams is providedRecord<string, string> mapping.params.parse method(rawParams: Record<string, string>) => TParams | falsefalse during incoming route matching skips this route and allows matching to continue to another candidate route.params.stringify method(params: TParams) => Record<string, string>Record<string, string> mapping.beforeLoad methodtype beforeLoad = (
opts: RouteMatch & {
search: TFullSearchSchema
abortController: AbortController
preload: boolean
params: TAllParams
context: TParentContext
location: ParsedLocation
navigate: NavigateFn<AnyRoute> // @deprecated
buildLocation: BuildLocationFn<AnyRoute>
cause: 'enter' | 'stay'
},
) => Promise<TRouteContext> | TRouteContext | void
ParsedLocationonError function. If thrown during a preload event, the error will be logged to the console and the preload will fail.pendingComponent will be shown until it resolves. If the promise rejects, the route will be put into an error state and the error will be thrown during render.TRouteContext object, that object will be merged into the route's context and be made available in the loader and other related route components/methods.redirect object from this function.🚧
opts.navigatehas been deprecated and will be removed in the next major release. Usethrow redirect({ to: '/somewhere' })instead. Read more about theredirectfunction here.
loader methodtype loaderFn = (
opts: RouteMatch & {
abortController: AbortController
cause: 'preload' | 'enter' | 'stay'
context: TAllContext
deps: TLoaderDeps
location: ParsedLocation
params: TAllParams
preload: boolean
parentMatchPromise: Promise<MakeRouteMatchFromRoute<TParentRoute>>
navigate: NavigateFn<AnyRoute> // @deprecated
route: AnyRoute
},
) => Promise<TLoaderData> | TLoaderData | void
type loader =
| loaderFn
| {
handler: loaderFn
staleReloadMode?: 'background' | 'blocking'
}
ParsedLocationonError function. If thrown during a preload event, the error will be logged to the console and the preload will fail.pendingComponent will be shown until it resolves. If the promise rejects, the route will be put into an error state and the error will be thrown during render.TLoaderData object, that object will be stored on the route match until the route match is no longer active. It can be accessed using the useLoaderData hook in any component that is a child of the route match before another <Outlet /> is rendered.loaderDeps function in order to appear.staleReloadMode.staleReloadMode: 'background' preserves stale-while-revalidate behavior for stale successful matches.staleReloadMode: 'blocking' waits for the stale loader reload to complete before continuing.🚧
opts.navigatehas been deprecated and will be removed in the next major release. Usethrow redirect({ to: '/somewhere' })instead. Read more about theredirectfunction here.
loaderDeps methodtype loaderDeps = (opts: { search: TFullSearchSchema }) => Record<string, any>
loader's deps argument.staleTime propertynumberrouterOptions.defaultStaleTime, which defaults to 0preloadStaleTime propertynumberrouterOptions.defaultPreloadStaleTime, which defaults to 30_000 ms (30 seconds)staleTime is used instead.gcTime propertynumberrouterOptions.defaultGcTime, which defaults to 30 minutes.shouldReload propertyboolean | ((args: LoaderArgs) => boolean)false or returns false, the route match's loader data will not be reloaded on subsequent matches.true or returns true, the route match's loader data will be reloaded on subsequent matches.undefined or returns undefined, the route match's loader data will adhere to the default stale-while-revalidate behavior.caseSensitive propertybooleantrue, this route will be matched as case-sensitive.wrapInSuspense propertybooleantrue, this route will be forcefully wrapped in a suspense boundary, regardless if a reason is found to do so from inspecting its provided components.pendingMs propertynumberrouterOptions.defaultPendingMs, which defaults to 1000pendingComponent is shown.pendingMinMs propertynumberrouterOptions.defaultPendingMinMs which defaults to 500preloadMaxAge propertynumber30_000 ms (30 seconds)preSearchFilters property (⚠️ deprecated, use search.middlewares instead)((search: TFullSearchSchema) => TFullSearchSchema)[]pre prefix because it is called before the user-provided function that is passed to navigate/Link etc has a chance to modify the search params.postSearchFilters property (⚠️ deprecated, use search.middlewares instead)((search: TFullSearchSchema) => TFullSearchSchema)[]post prefix because it is called after the user-provided function that is passed to navigate/Link etc has modified the search params.onError property(error: any) => voidredirect, then the router will process and apply the redirect immediately.onEnter property(match: RouteMatch) => voidonStay property(match: RouteMatch) => voidonLeave property(match: RouteMatch) => voidonCatch property(error: Error, errorInfo: ErrorInfo) => voidrouterOptions.defaultOnCatchremountDeps methodtype remountDeps = (opts: RemountDepsOptions) => any
interface RemountDepsOptions<
in out TRouteId,
in out TFullSearchSchema,
in out TAllParams,
in out TLoaderDeps,
> {
routeId: TRouteId
search: TFullSearchSchema
params: TAllParams
loaderDeps: TLoaderDeps
}
Example:
If you want to configure to remount a route component upon params change, use:
remountDeps: ({ params }) => params
headers methodtype headers = (opts: {
matches: Array<RouteMatch>
match: RouteMatch
params: TAllParams
loaderData?: TLoaderData
}) => Promise<Record<string, string>> | Record<string, string>
head methodtype head = (ctx: {
matches: Array<RouteMatch>
match: RouteMatch
params: TAllParams
loaderData?: TLoaderData
}) =>
| Promise<{
links?: RouteMatch['links']
scripts?: RouteMatch['headScripts']
meta?: RouteMatch['meta']
styles?: RouteMatch['styles']
}>
| {
links?: RouteMatch['links']
scripts?: RouteMatch['headScripts']
meta?: RouteMatch['meta']
styles?: RouteMatch['styles']
}
<head> for this route. Use it to add route-level SEO metadata, preload links, inline styles, or custom scripts.scripts methodtype scripts = (ctx: {
matches: Array<RouteMatch>
match: RouteMatch
params: TAllParams
loaderData?: TLoaderData
}) => Promise<RouteMatch['scripts']> | RouteMatch['scripts']
<script> elements. Equivalent to returning the scripts field from the head method.codeSplitGroupings propertyArray<Array<'loader' | 'component' | 'pendingComponent' | 'notFoundComponent' | 'errorComponent'>>The Route type is used to describe a route instance.
Route properties and methodsAn instance of the Route has the following properties and methods:
.addChildren method(children: Route[]) => this.update method(options: Partial<UpdatableRouteOptions>) => thisRouteApi methods.lazy method(lazyImporter: () => Promise<Partial<UpdatableRouteOptions>>) => this.redirect method(opts?: RedirectOptions) => Redirectredirect function that is pre-bound to the route's path.from parameter is automatically set to the route's fullPath, enabling type-safe relative redirects.RouteApi.redirect for more details.import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/dashboard/settings')({
beforeLoad: ({ context }) => {
if (!context.user) {
// Type-safe redirect - 'from' is automatically '/dashboard/settings'
throw Route.redirect({
to: '../login', // Relative path to sibling route
})
}
},
})
RouteApi methodsRouteApi are available.[!CAUTION] This class has been deprecated and will be removed in the next major version of TanStack Router. Please use the
createRouterfunction instead.
The Router class is used to instantiate a new router instance.
Router constructorThe Router constructor accepts a single argument: the options that will be used to configure the router instance.
RouterOptionsRouter.import { Router, RouterProvider } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
const router = new Router({
routeTree,
defaultPreload: 'intent',
})
export default function App() {
return <RouterProvider router={router} />
}
The RouterEvents type contains all of the events that the router can emit. Each top-level key of this type, represents the name of an event that the router can emit. The values of the keys are the event payloads.
type RouterEvents = {
onBeforeNavigate: {
type: 'onBeforeNavigate'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
hashChanged: boolean
}
onBeforeLoad: {
type: 'onBeforeLoad'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
hashChanged: boolean
}
onLoad: {
type: 'onLoad'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
hashChanged: boolean
}
onResolved: {
type: 'onResolved'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
hashChanged: boolean
}
onBeforeRouteMount: {
type: 'onBeforeRouteMount'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
hashChanged: boolean
}
onInjectedHtml: {
type: 'onInjectedHtml'
}
onRendered: {
type: 'onRendered'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
hashChanged: boolean
}
}
Once an event is emitted, the following properties will be present on the event payload.
type propertyonBeforeNavigate | onBeforeLoad | onLoad | onBeforeRouteMount | onResolved | onRendered | onInjectedHtmlfromLocation propertyParsedLocationtoLocation propertyParsedLocationpathChanged propertybooleantrue if the path has changed between the fromLocation and toLocation.hrefChanged propertybooleantrue if the href has changed between the fromLocation and toLocation.hashChanged propertybooleantrue if the hash has changed between the fromLocation and toLocation.import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
const router = createRouter({ routeTree })
const unsub = router.subscribe('onResolved', (evt) => {
// ...
})
The RouterOptions type contains all of the options that can be used to configure a router instance.
The RouterOptions type accepts an object with the following properties and methods:
routeTree propertyAnyRoutehistory propertyRouterHistorycreateBrowserHistory instance will be created and used.stringifySearch method(search: Record<string, any>) => stringdefaultStringifySearch.parseSearch method(search: string) => Record<string, any>defaultParseSearch.search.strict propertybooleanfalsevalidateSearch) are treated.false, unknown search params will be kept.true, unknown search params will be removed.defaultPreload propertyundefined | false | 'intent' | 'viewport' | 'render'falsefalse, routes will not be preloaded by default in any way.'intent', routes will be preloaded by default when the user hovers over a link or a touchstart event is detected on a <Link>.'viewport', routes will be preloaded by default when they are within the viewport of the browser.'render', routes will be preloaded by default as soon as they are rendered in the DOM.defaultPreloadDelay propertynumber50defaultComponent propertyRouteComponentOutletcomponent a route should use if no component is provided.defaultErrorComponent propertyRouteComponentErrorComponenterrorComponent a route should use if no error component is provided.defaultNotFoundComponent propertyNotFoundRouteComponentNotFoundnotFoundComponent a route should use if no notFound component is provided.defaultPendingComponent propertyRouteComponentpendingComponent a route should use if no pending component is provided.defaultPendingMs propertynumber1000pendingMs a route should use if no pendingMs is provided.defaultPendingMinMs propertynumber500pendingMinMs a route should use if no pendingMinMs is provided.defaultStaleTime propertynumber0staleTime a route should use if no staleTime is provided.defaultStaleReloadMode property'background' | 'blocking''background''background' preserves stale-while-revalidate behavior.'blocking' waits for the stale loader reload to finish before navigation resolves.defaultPreloadStaleTime propertynumber30_000 ms (30 seconds)preloadStaleTime a route should use if no preloadStaleTime is provided.defaultPreloadGcTime propertynumberrouterOptions.defaultGcTime, which defaults to 30 minutes.preloadGcTime a route should use if no preloadGcTime is provided.defaultGcTime propertynumbergcTime a route should use if no gcTime is provided.defaultOnCatch property(error: Error, errorInfo: ErrorInfo) => voidonCatch handler for errors caught by the Router ErrorBoundarydisableGlobalCatchBoundary propertybooleanfalsetrue, disables the global catch boundary that normally wraps all route matches. This allows unhandled errors to bubble up to top-level error handlers in the browser.protocolAllowlist propertyArray<string>DEFAULT_PROTOCOL_ALLOWLIST which includes:
http:, https:mailto:, tel:<Link to="...">navigate({ to: ... }) and navigate({ href: ... })redirect({ to: ... }) and redirect({ href: ... })URL.protocol format (lowercase with a trailing :), for example blob: or data:. If you configure protocolAllowlist: ['blob'] (without :), links using blob: will still be blocked.Example
import {
createRouter,
DEFAULT_PROTOCOL_ALLOWLIST,
} from '@tanstack/react-router'
// Use a custom allowlist (replaces the default)
const router = createRouter({
routeTree,
protocolAllowlist: ['https:', 'mailto:'],
})
// Or extend the default allowlist
const router = createRouter({
routeTree,
protocolAllowlist: [...DEFAULT_PROTOCOL_ALLOWLIST, 'ftp:'],
})
defaultViewTransition propertyboolean | ViewTransitionOptionstrue, route navigations will be called using document.startViewTransition().ViewTransitionOptions, route navigations will be called using document.startViewTransition({update, types})
where types will be the strings array passed with ViewTransitionOptions["types"]. If the browser does not support viewTransition types,
the navigation will fall back to normal document.startTransition(), same as if true was passed.defaultHashScrollIntoView propertyboolean | ScrollIntoViewOptionstrue so the element with an id matching the hash will be scrolled into view after the location is committed to history.false, the element with an id matching the hash will not be scrolled into view after the location is committed to history.scrollIntoView method as options.ScrollIntoViewOptions.caseSensitive propertybooleanfalsetrue, all routes will be matched as case-sensitive.basepath propertystring/rewrite propertyLocationRewriteThe LocationRewrite type has the following shape:
type LocationRewrite = {
input?: LocationRewriteFunction
output?: LocationRewriteFunction
}
type LocationRewriteFunction = (opts: { url: URL }) => undefined | string | URL
input: Transforms the URL before the router interprets it (browser → router)output: Transforms the URL before it's written to browser history (router → browser)Example
import { createRouter } from '@tanstack/react-router'
const router = createRouter({
routeTree,
rewrite: {
input: ({ url }) => {
// Strip locale prefix: /en/about → /about
if (url.pathname.startsWith('/en')) {
url.pathname = url.pathname.replace(/^\/en/, '') || '/'
}
return url
},
output: ({ url }) => {
// Add locale prefix: /about → /en/about
url.pathname = `/en${url.pathname === '/' ? '' : url.pathname}`
return url
},
},
})
When both basepath and rewrite are configured, they are automatically composed. The basepath rewrite runs first on input (stripping the basepath) and last on output (adding it back).
context propertyanycreateRootRouteWithContext().dehydrate method() => TDehydratedhydrate method(dehydrated: TDehydrated) => voidrouteMasks propertyRouteMask[]unmaskOnReload propertybooleanfalsetrue, route masks will, by default, be removed when the page is reloaded. This can be overridden on a per-mask basis by setting unmaskOnReload on the mask, or on a per-navigation basis by setting mask.unmaskOnReload in NavigateOptions.Wrap propertyReact.ComponentExample
import { createRouter } from '@tanstack/react-router'
const router = createRouter({
// ...
Wrap: ({ children }) => {
return <MyContext.Provider value={myContext}>{children}</MyContext>
},
})
InnerWrap propertyReact.ComponentExample
import { createRouter } from '@tanstack/react-router'
const router = createRouter({
// ...
InnerWrap: ({ children }) => {
const routerState = useRouterState()
return (
<MyContext.Provider value={myContext}>
{children}
</MyContext>
)
},
})
notFoundMode property'root' | 'fuzzy''fuzzy'notFoundRoute propertyNotFoundRouteNotFoundRoute option on the root route of the branch.trailingSlash property'always' | 'never' | 'preserve'never'always' will add a trailing slash if not present, 'never' will remove the trailing slash if present and 'preserve' will not modify the trailing slash.pathParamsAllowedCharacters propertyArray<';' | ':' | '@' | '&' | '=' | '+' | '$' | ','>defaultStructuralSharing propertybooleanfalsedefaultRemountDeps propertytype defaultRemountDeps = (opts: RemountDepsOptions) => any
interface RemountDepsOptions<
in out TRouteId,
in out TFullSearchSchema,
in out TAllParams,
in out TLoaderDeps,
> {
routeId: TRouteId
search: TFullSearchSchema
params: TAllParams
loaderDeps: TLoaderDeps
}
Example:
If you want to configure to remount all route components upon params change, use:
remountDeps: ({ params }) => params
The RouterState type represents shape of the internal state of the router. The Router's internal state is useful, if you need to access certain internals of the router, such as any pending matches, is the router in its loading state, etc.
type RouterState = {
status: 'pending' | 'idle'
isLoading: boolean
isTransitioning: boolean
matches: Array<RouteMatch>
location: ParsedLocation
resolvedLocation: ParsedLocation
}
The RouterState type contains all of the properties that are available on the router state.
status property'pending' | 'idle'isLoading propertybooleantrue if the router is currently loading a route or waiting for a route to finish loading.isTransitioning propertybooleantrue if the router is currently transitioning to a new route.matches propertyArray<RouteMatch>location propertyParsedLocationresolvedLocation propertyParsedLocationThe Router type is used to describe a router instance.
Router properties and methodsAn instance of the Router has the following properties and methods:
.update method(newOptions: RouterOptions) => voidstate propertyRouterState⚠️⚠️⚠️
router.stateis always up to date, but NOT REACTIVE. If you userouter.statein a component, the component will not re-render when the router state changes. To get a reactive version of the router state, use theuseRouterStatehook.
.subscribe method(eventType: TType, fn: ListenerFn<RouterEvents[TType]>) => () => voidRouterEvent..matchRoutes method(pathname: string, locationSearch?: Record<string, any>, opts?: { throwOnError?: boolean; }) => RouteMatch[]opts.throwOnError is true, any errors that occur during the matching process will be thrown (in addition to being returned in the route match's error property)..cancelMatch method(matchId: string) => voidmatch.abortController.abort()..cancelMatches method() => voidmatch.abortController.abort() on each one..buildLocation methodBuilds a new parsed location object that can be used later to navigate to a new location.
(opts: BuildNextOptions) => ParsedLocationfrom
stringto
string | number | nullnull, the current path will be used.params
true | Updater<unknown>true, the current params will be used. If a function is provided, it will be called with the current params and the return value will be used.search
true | Updater<unknown>true, the current search params will be used. If a function is provided, it will be called with the current search params and the return value will be used.hash
true | Updater<string>true, the current hash will be used. If a function is provided, it will be called with the current hash and the return value will be used.state
true | NonNullableUpdater<ParsedHistoryState, HistoryState>true, the current state will be used. If a function is provided, it will be called with the current state and the return value will be used.mask
objectunmaskOnReload.unmaskOnReload
booleantrue, the route mask will be removed when the page is reloaded. This can be overridden on a per-navigation basis by setting mask.unmaskOnReload in NavigateOptions..commitLocation methodCommits a new location object to the browser history.
type commitLocation = (
location: ParsedLocation & {
replace?: boolean
resetScroll?: boolean
hashScrollIntoView?: boolean | ScrollIntoViewOptions
ignoreBlocker?: boolean
},
) => Promise<void>
location
ParsedLocationreplace
booleanfalse.true, the location will be committed to the browser history using history.replace instead of history.push.resetScroll
booleantrue so that the scroll position will be reset to 0,0 after the location is committed to the browser history.false, the scroll position will not be reset to 0,0 after the location is committed to history.hashScrollIntoView
boolean | ScrollIntoViewOptionstrue so the element with an id matching the hash will be scrolled into view after the location is committed to history.false, the element with an id matching the hash will not be scrolled into view after the location is committed to history.scrollIntoView method as options.ScrollIntoViewOptions.ignoreBlocker
booleanfalse.true, navigation will ignore any blockers that might prevent it..navigate methodNavigates to a new location.
type navigate = (options: NavigateOptions) => Promise<void>
.invalidate methodInvalidates route matches by forcing their beforeLoad and load functions to be called again.
(opts?: {filter?: (d: MakeRouteMatchUnion<TRouter>) => boolean, sync?: boolean, forcePending?: boolean }) => Promise<void>filter is not supplied, all matches will be invalidatedfilter is supplied, only matches for which filter returns true will be invalidated.sync is true, the promise returned by this function will only resolve once all loaders have finished.forcePending is true, the invalidated matches will be put into 'pending' state regardless whether they are in 'error' state or not.reset the router's CatchBoundary to trigger loaders again..clearCache methodRemove cached route matches.
(opts?: {filter?: (d: MakeRouteMatchUnion<TRouter>) => boolean}) => voidfilter is not supplied, all cached matches will be removedfilter is supplied, only matches for which filter returns true will be removed..load methodLoads all of the currently matched route matches and resolves when they are all loaded and ready to be rendered.
⚠️⚠️⚠️
router.load()respectsroute.staleTime: fresh matches stay fresh, but stale matches are revalidated even if their loader key did not change. If you need to forcefully reload all active matches regardless of freshness, userouter.invalidate()instead.
(opts?: {sync?: boolean}) => Promise<void>sync is true, the promise returned by this function will only resolve once all loaders have finished..preloadRoute methodPreloads all of the matches that match the provided NavigateOptions.
⚠️⚠️⚠️ Preloaded route matches are not stored long-term in the router state. They are only stored until the next attempted navigation action.
(opts?: NavigateOptions) => Promise<RouteMatch[]>opts
NavigateOptions.loadRouteChunk methodLoads the JS chunk of the route.
(route: AnyRoute) => Promise<void>.matchRoute methodMatches a pathname and search params against the router's route tree and returns a route match's params or false if no match was found.
(dest: ToOptions, matchOpts?: MatchRouteOptions) => RouteMatch['params'] | falsedest
ToOptionsmatchOpts
MatchRouteOptionsfalse if no match was found..dehydrate methodDehydrates the router's critical state into a serializable object that can be sent to the client in an initial request.
() => DehydratedRouter.hydrate methodHydrates the router's critical state from a serializable object that was sent from the server in an initial request.
(dehydrated: DehydratedRouter) => voiddehydrated
DehydratedRouterThe ToMaskOptions type includes the same destination fields as ToOptions, excluding mask, and adds options specific to route masking.
type ToMaskOptions = {
from?: ValidRoutePath | string
to?: ValidRoutePath | string
hash?: true | string | ((prev?: string) => string)
state?: true | HistoryState | ((prev: HistoryState) => HistoryState)
} & SearchParamOptions &
PathParamOptions & {
unmaskOnReload?: boolean
}
The ToOptions type contains several properties that can be used to describe a router destination, including mask for route masking.
type ToOptions = {
from?: ValidRoutePath | string
to?: ValidRoutePath | string
hash?: true | string | ((prev?: string) => string)
state?: true | HistoryState | ((prev: HistoryState) => HistoryState)
} & SearchParamOptions &
PathParamOptions &
MaskOptions
type SearchParamOptions = {
search?: true | TToSearch | ((prev: TFromSearch) => TToSearch)
}
type PathParamOptions = {
params?:
| true
| Record<string, TPathParam>
| ((prev: TFromParams) => TToParams)
}
type MaskOptions = {
mask?: ToMaskOptions<TRouter, TMaskFrom, TMaskTo>
}
The UseMatchRouteOptions type extends the ToOptions type and describes additional options available when using the useMatchRoute hook.
export type UseMatchRouteOptions = ToOptions & MatchRouteOptions
The ViewTransitionOptions type is used to define a
viewTransition type.
interface ViewTransitionOptions {
types:
| Array<string>
| ((locationChangeInfo: {
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
hashChanged: boolean
}) => Array<string> | false)
}
The ViewTransitionOptions type accepts an object with a single property:
types propertyArray<string> | ((locationChangeInfo: { fromLocation?: ParsedLocation toLocation: ParsedLocation pathChanged: boolean hrefChanged: boolean hashChanged: boolean }) => (Array<string> | false))document.startViewTransition({update, types}) calllocationChangeInfo object and returns either:
document.startViewTransition({update, types}) callfalse to skip the view transitionThe Await component is a component that suspends until the provided promise is resolved or rejected.
This is only necessary for React 18.
If you are using React 19, you can use the use() hook instead.
The Await component accepts the following props:
props.promise propPromise<T>props.children prop(result: T) => React.ReactNode