Browse documentation
Agent docs/router/typed-router-context
contract

Establish typed Router Context

Declare dependencies at the root and use beforeLoad to add inferred derived context to a subtree.

View raw Markdown
CONTRACT

Execution contract

Use when
Use when loaders, beforeLoad, and route components share QueryClient, auth readers, or other app dependencies.
Avoid when
Do not put frequently changing page state or component-local data in Router Context.
Preconditions
Register the smallest dependency interface and decide how the value is obtained outside RouterProvider.
Verification
Missing required dependencies fail compilation and context extended by parent beforeLoad remains typed in children.
Failure mode
Context becoming any usually comes from missing module registration or a cast at router creation.
Security
Context can carry auth capabilities, but client auth state is not server authorization evidence.
01

Root contract

Declare root dependencies with createRootRouteWithContext<RouterContext>(). createRouter.context must satisfy that type; do not hide a genuinely missing service behind a non-null assertion.

src/routes/__root.tsxtsx
import { createRootRouteWithContext } from '@tanstack/react-router'
import type { QueryClient } from '@tanstack/react-query'

type RouterContext = { queryClient: QueryClient }

export const Route = createRootRouteWithContext<RouterContext>()({
  component: RootDocument,
})
02

Subtree extension

beforeLoad may return new context synchronously or asynchronously. Router merges it with parent context for child routes. Return only stable facts the subtree needs so each loader does not repeat the work.

03

Authorization boundary

beforeLoad can stop or redirect navigation, but client route state can be bypassed. Server data entry points must independently authenticate and authorize; a context boolean such as canEdit is not proof of authorization.

PRIMARY SOURCEShttps://tanstack.com/router/latest/docs/guide/router-contexthttps://tanstack.com/router/latest/docs/framework/react/guide/authenticated-routes
TanStack Atlas

Original bilingual knowledge · verified against primary sources

Friend linksGitHub