---
id: router.typed-context
kind: contract
product: router
framework: react
locale: en
revision: 2
sourceCheckedOn: "2026-08-03"
versionRange: "^1"
verifiedAgainst: "@tanstack/react-router@1.170.18"
contentModel: 2
packages:
  - "@tanstack/react-router"
tasks:
  - "inject-router-dependency"
  - "augment-route-context"
  - "before-load-context"
sourceRefs:
  - "https://tanstack.com/router/latest/docs/guide/router-context"
  - "https://tanstack.com/router/latest/docs/framework/react/guide/authenticated-routes"
---

# Establish typed Router Context

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

## 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.

## 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.

File: `src/routes/__root.tsx`

```tsx
import { createRootRouteWithContext } from '@tanstack/react-router'
import type { QueryClient } from '@tanstack/react-query'

type RouterContext = { queryClient: QueryClient }

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

## 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.

## 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.

## Official sources

- https://tanstack.com/router/latest/docs/guide/router-context
- https://tanstack.com/router/latest/docs/framework/react/guide/authenticated-routes
