---
id: route-context
track: learn
product: router
locale: en
order: 9
revision: 2
sourceCheckedOn: "2026-08-03"
versionRange: "Router ^1"
verifiedAgainst: "@tanstack/react-router@1.170.18"
contentModel: 2
prerequisites:
  - "Root and nested route basics"
  - "TypeScript interfaces"
sourceRefs:
  - "https://tanstack.com/router/latest/docs/guide/router-context"
  - "https://tanstack.com/router/latest/docs/framework/react/guide/authenticated-routes"
---

# Pass dependencies through Router Context

> Declare typed dependencies at the root, then use beforeLoad to add inferred context for a route subtree.

**Outcome:** Define typed Router Context for a QueryClient, session, or service and explain its boundary with server authorization.

## Declare the smallest root contract

createRootRouteWithContext makes the route tree require the same dependencies from createRouter. Put stable dependencies shared by loaders, beforeLoad, and route components here, not arbitrary component state.

File: `src/routes/__root.tsx`

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

type RouterContext = {
  queryClient: QueryClient
  session: { permissions: readonly string[] }
}

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

## Let a parent route add derived facts

The value returned by beforeLoad is merged into context for that route and its children. A parent computes canEditIssues once, so child loaders do not reinterpret permission strings and still receive complete inference.

> **Note:** Client-side beforeLoad improves navigation UX but is not a data authorization boundary; Server Functions and Server Routes must authorize again.

File: `src/routes/_workspace.tsx`

```tsx
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/_workspace')({
  beforeLoad: ({ context }) => ({
    canEditIssues: context.session.permissions.includes('issues:write'),
  }),
})
```

## Practice and verification

### Completion checkpoint

Router Context dependencies are injected at router creation and remain typed in beforeLoad and loaders.

### Exercise

Add QueryClient and an auth-reader interface to root context, then consume them from a protected route.

### Verification

Removing a required dependency should fail router creation at typecheck; restoring it should expose the same instance to loaders.

### Common pitfalls

- Calling a React hook at route-module scope.
- Using any to bypass Router Context registration.

## Official sources

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