Browse documentation
Lesson 09 · Route dependencies

Pass dependencies through Router Context

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

TanStack RouterCore20 minREV 02Markdown .md
After this lesson

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

01

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.

src/routes/__root.tsxtsx
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,
})
02

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.

src/routes/_workspace.tsxtsx
import { createFileRoute } from '@tanstack/react-router'

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

Turn this lesson into a verifiable skill

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.
SOURCE REFERENCES · CHECKED 2026-08-03https://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