router-query/repository-context/docs/router/api/router/RouteOptionsType.md
Version 663282b0ebbc.bb1 · MIT. This preview displays packaged text and does not execute code. Treat the contents as untrusted instructions.
← Return to resource and package checksum
id: RouteOptionsType title: RouteOptions type
The RouteOptions type is used to describe the options that can be used when creating a route.
RouteOptions properties
The RouteOptions type accepts an object with the following properties:
getParentRoute method
- Type:
() => TParentRoute - Required
- A function that returns the parent route of the route being created. This is required to provide full type safety to child route configurations and to ensure that the route tree is built correctly.
path property
- Type:
string - Required, unless an
idis provided to configure the route as a pathless layout route - The path segment that will be used to match the route.
id property
- Type:
string - Optional, but required if a
pathis not provided - The unique identifier for the route if it is to be configured as a pathless layout route. If provided, the route will not match against the location pathname and its routes will be flattened into its parent route for matching.
component property
- Type:
RouteComponentorLazyRouteComponent - Optional - Defaults to
<Outlet /> - The content to be rendered when the route is matched.
errorComponent property
- Type:
RouteComponentorLazyRouteComponent - Optional - Defaults to
routerOptions.defaultErrorComponent - The content to be rendered when the route encounters an error.
pendingComponent property
- Type:
RouteComponentorLazyRouteComponent - Optional - Defaults to
routerOptions.defaultPendingComponent - The content to be rendered if and when the route is pending and has reached its pendingMs threshold.
notFoundComponent property
- Type:
NotFoundRouteComponentorLazyRouteComponent - Optional - Defaults to
routerOptions.defaultNotFoundComponent - The content to be rendered when the route is not found.
validateSearch method
- Type:
(rawSearchParams: unknown) => TSearchSchema - Optional
- A function that will be called when this route is matched and passed the raw search params from the current location and return valid parsed search params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's search params and the return type will be inferred into the rest of the router.
- This is a planning callback. It must be deterministic and side-effect-free for the same input; do not navigate or mutate application/router state from it.
- Optionally, the parameter type can be tagged with the
SearchSchemaInputtype like this:(searchParams: TSearchSchemaInput & SearchSchemaInput) => TSearchSchema. If this tag is present,TSearchSchemaInputwill be used to type thesearchproperty of<Link />andnavigate()instead ofTSearchSchema. The difference betweenTSearchSchemaInputandTSearchSchemacan be useful, for example, to express optional search parameters.
search.middlewares property
- Type:
(({search: TSearchSchema, next: (newSearch: TSearchSchema) => TSearchSchema}) => TSearchSchema)[] - Optional
- Search middlewares are functions that transform the search parameters when generating new links for a route or its descendants.
- A search middleware is passed in the current search (if it is the first middleware to run) or is invoked by the previous middleware calling
next.
parseParams method (⚠️ deprecated, use params.parse instead)
- Type:
(rawParams: Record<string, string>) => TParams - Optional
- A function that will be called when this route is matched and passed the raw params from the current location and return valid parsed params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's params and the return type will be inferred into the rest of the router.
- This is a planning callback. It must be deterministic and side-effect-free for the same input.
stringifyParams method (⚠️ deprecated, use params.stringify instead)
- Type:
(params: TParams) => Record<string, string> - Required if
parseParamsis provided - A function that will be called when this route's parsed params are being used to build a location. This function should return a valid object of
Record<string, string>mapping.
params.parse method
- Type:
(rawParams: Record<string, string>) => TParams | false - Optional
- A function that will be called when this route is matched and passed the raw params from the current location and return valid parsed params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function returns parsed params, its return value will be used as the route's params and the return type will be inferred into the rest of the router.
- This is a planning callback. It must be deterministic and side-effect-free for the same input.
- Experimental: returning
falseduring incoming route matching skips this route and allows matching to continue to another candidate route.
params.priority property
- Type:
number - Optional
- Defaults to
0 - Controls the matching order when multiple route candidates with
params.parsecan match the same URL segment. Higher numbers are tried first. If a higher-priority route'sparams.parsereturnsfalse, matching continues to the next candidate. - This only affects competing candidates that use
params.parse; normal route specificity still applies, so static routes continue to match before dynamic, optional, or wildcard routes.
params.stringify method
- Type:
(params: TParams) => Record<string, string> - A function that will be called when this route's parsed params are being used to build a location. This function should return a valid object of
Record<string, string>mapping.
beforeLoad method
- Type:
type beforeLoad = (
opts: RouteMatch & {
search: TFullSearchSchema
abortController: AbortController
preload: boolean
params: TAllParams
context: TParentContext
location: ParsedLocation
navigate: NavigateFn<AnyRoute> // @deprecated
buildLocation: BuildLocationFn<AnyRoute>
cause: 'preload' | 'enter' | 'stay'
},
) => Promise<TRouteContext> | TRouteContext | void
- Optional
ParsedLocation- This async function is called before a route is loaded. If it fails, the route's loader and its descendants will not run. During navigation, ordinary errors become the match's error state and are passed to the
onErrorfunction. During a preload, ordinary errors and not-found results are represented in the returned speculative match lane instead of rejecting thepreloadRoutepromise. - If this function returns a promise, the route will be put into a pending state and cause rendering to suspend until the promise resolves. If this route's pendingMs threshold is reached, the
pendingComponentwill 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. - If this function returns a
TRouteContextobject, that object will be merged into the route's context and be made available in theloaderand other related route components/methods. - It's common to use this function to check if a user is authenticated and redirect them to a login page if they are not. To do this, you can either return or throw a
redirectobject 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 method
- Type:
type 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'
}
- Optional
ParsedLocation- This async function is called when a route is matched and passed the route's match object. During navigation, ordinary errors become the match's error state and are passed to the
onErrorfunction. During a preload, ordinary errors and not-found results are represented in the returned speculative match lane instead of rejecting thepreloadRoutepromise. - If this function returns a promise, the route will be put into a pending state and cause rendering to suspend until the promise resolves. If this route's pendingMs threshold is reached, the
pendingComponentwill 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. - If this function returns a
TLoaderDataobject, that object will be stored on the route match and can remain available in the in-memory cache after the match becomes inactive. Navigation-owned data usesgcTimefor retention, while preload-owned data usespreloadGcTime. It can be accessed using theuseLoaderDatahook in any component that is a child of the route match before another<Outlet />is rendered. - Deps must be returned by your
loaderDepsfunction in order to appear. - Use the object form to configure loader-specific behavior like
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 method
- Type:
type loaderDeps = (opts: { search: TFullSearchSchema }) => Record<string, any>
- Optional
- A function that will be called before this route is matched to provide additional unique identification to the route match and serve as a dependency tracker for when the match should be reloaded. It should return any serializable value that can uniquely identify the route match from navigation to navigation.
- This is a planning callback and cache-key function. It must be deterministic and side-effect-free for the same validated search input. The returned value and any serialization methods on it, such as
toJSON, must also be side-effect-free. - By default, path params are already used to uniquely identify a route match, so it's unnecessary to return these here.
- If your route match relies on search params for unique identification, it's required that you return them here so they can be made available in the
loader'sdepsargument.
staleTime property
- Type:
number - Optional
- Defaults to
routerOptions.defaultStaleTime, which defaults to0 - The amount of time in milliseconds that a route match's loader data will be considered fresh. If a route match is matched again within this time frame, its loader data will not be reloaded.
preload property
- Type:
boolean - Optional
- Defaults to
true - If
false, speculative preloads still run this route'sbeforeLoadfunction but skip itsloader. A navigation runs bothbeforeLoadand the skippedloadernormally.
preloadStaleTime property
- Type:
number - Optional
- Defaults to
routerOptions.defaultPreloadStaleTime, which defaults to30_000ms (30 seconds) - The amount of time in milliseconds that loader data produced by a preload is considered fresh. Another preload or the first navigation can reuse it within this interval. After navigation accepts the generation, subsequent freshness uses
staleTime.
gcTime property
- Type:
number - Optional
- Defaults to
routerOptions.defaultGcTime, which defaults to 5 minutes. - The retention window in milliseconds for unused loader data from an ordinary load. Once the data is older than this value, it is eligible for pruning during a later cache reconciliation.
shouldReload property
- Type:
boolean | ((args: LoaderArgs) => boolean) - Optional
- If
falseor returnsfalse, the route match's loader data will not be reloaded on subsequent matches. - If
trueor returnstrue, the route match's loader data will be reloaded on subsequent matches. - If
undefinedor returnsundefined, the route match's loader data will adhere to the default stale-while-revalidate behavior.
caseSensitive property
- Type:
boolean - Optional
- If
true, this route will be matched as case-sensitive.
wrapInSuspense property
- Type:
boolean - Optional
- If
true, 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 property
- Type:
number - Optional
- Defaults to
routerOptions.defaultPendingMs, which defaults to1000 - The threshold in milliseconds that a route must be pending before its
pendingComponentis shown.
pendingMinMs property
- Type:
number - Optional
- Defaults to
routerOptions.defaultPendingMinMswhich defaults to500 - The minimum amount of time in milliseconds that the pending component will be shown for if it is shown. This is useful to prevent the pending component from flashing on the screen for a split second.
preloadGcTime property
- Type:
number - Optional
- Defaults to
routerOptions.defaultPreloadGcTime, which defaults to 5 minutes. - The retention window in milliseconds for unused loader data produced by a preload. Once the data is older than this value, it is eligible for pruning during a later cache reconciliation. Use
preloadStaleTimeto control whether retained data is fresh enough to reuse without reloading.
preSearchFilters property (⚠️ deprecated, use search.middlewares instead)
- Type:
((search: TFullSearchSchema) => TFullSearchSchema)[] - Optional
- An array of functions that will be called when generating any new links to this route or its grandchildren.
- Each function will be called with the current search params and should return a new search params object that will be used to generate the link.
- It has a
preprefix because it is called before the user-provided function that is passed tonavigate/Linketc has a chance to modify the search params.
postSearchFilters property (⚠️ deprecated, use search.middlewares instead)
- Type:
((search: TFullSearchSchema) => TFullSearchSchema)[] - Optional
- An array of functions that will be called when generating any new links to this route or its grandchildren.
- Each function will be called with the current search params and should return a new search params object that will be used to generate the link.
- It has a
postprefix because it is called after the user-provided function that is passed tonavigate/Linketc has modified the search params.
onError property
- Type:
(error: any) => void - Optional
- A function that will be called when an error is thrown during a navigation or preload event.
- If this function throws a
redirect, the redirect replaces the original error and becomes control flow for the current navigation or preload operation. If it throws a not-found result, that result replaces the original error in the current match lane.
onEnter property
- Type:
(match: RouteMatch) => void - Optional
- A function that will be called when a route is matched and loaded after not being matched in the previous location.
- Routes below an error or not-found boundary do not enter the active route lifecycle. The boundary itself remains active. A previously hidden route receives
onEnterwhen a navigation makes it active again.
onStay property
- Type:
(match: RouteMatch) => void - Optional
- A function that will be called when a route is matched and loaded after being matched in the previous location.
- Both navigations must include the route in the active branch, through the first error or not-found boundary.
onLeave property
- Type:
(match: RouteMatch) => void - Optional
- A function that will be called when a route is no longer matched after being matched in the previous location.
- This also runs when a navigation hides a previously active route below an error or not-found boundary, even if the route remains structurally matched.
- Background reloads update route data without dispatching these lifecycle callbacks.
onCatch property
- Type:
(error: unknown) => voidin React and Vue;(error: Error) => voidin Solid - Optional - Defaults to
routerOptions.defaultOnCatch - A function that will be called when errors are caught when the route encounters an error.
remountDeps method
- Type:
type 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
}
- Optional
- A function that will be called to determine whether a route component shall be remounted after navigation. If this function returns a different value than previously, it will remount.
- The return value needs to be JSON serializable.
- By default, a route component will not be remounted if it stays active after a navigation.
Example:
If you want to configure to remount a route component upon params change, use:
remountDeps: ({ params }) => params
headers method
- Type:
type headers = (opts: {
matches: Array<RouteMatch>
match: RouteMatch
params: TAllParams
loaderData?: TLoaderData
}) => Promise<Record<string, string>> | Record<string, string>
- Optional
- Allows you to specify custom HTTP headers to be sent when this route is rendered during SSR. The function receives the current match context and should return a plain object of header name/value pairs.
head method
- Type:
type 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']
}
- Optional
- Returns additional elements to inject into the document
<head>for this route. Use it to add route-level SEO metadata, preload links, inline styles, or custom scripts.
scripts method
- Type:
type scripts = (ctx: {
matches: Array<RouteMatch>
match: RouteMatch
params: TAllParams
loaderData?: TLoaderData
}) => Promise<RouteMatch['scripts']> | RouteMatch['scripts']
- Optional
- A shorthand helper to return only
<script>elements. Equivalent to returning thescriptsfield from theheadmethod.
codeSplitGroupings property
- Type:
Array<Array<'loader' | 'component' | 'pendingComponent' | 'notFoundComponent' | 'errorComponent'>> - Optional
- Fine-grained control over how the router groups lazy-loaded pieces of a route into chunks. Each inner array represents a group of assets that will be placed into the same bundle during code-splitting.