Course contentsShow
← React
Lesson 1883 of 2,39643. RoutingFree lesson

Route Context and beforeLoad

Share typed context across route trees and implement authentication checks with beforeLoad hooks.

Route Context and beforeLoad

You'll learn how to share typed data across your route tree and run authentication or validation logic before a route loads.

What is Route Context?

In TanStack Router, route context is a way to pass shared, typed data down through your route hierarchy. Think of it like React's Context API, but scoped to routing: parent routes can inject values (user info, permissions, theme settings) that child routes automatically receive — all with full TypeScript inference.

The beforeLoad Hook

The beforeLoad function runs before a route's loader and component render. It's your gatekeeper: perfect for authentication checks, authorization logic, or fetching prerequisite data. You can read context, modify it, or throw/redirect to block navigation.

Here's the pattern:

const rootRoute = createRoute({
  // Parent provides context
  beforeLoad: async () => {
    const user = await getCurrentUser();
    return { user }; // Available to all child routes
  }
});

const dashboardRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/dashboard',
  beforeLoad: ({ context }) => {
    // Access parent context, perform auth check
    if (!context.user) {
      throw redirect({ to: '/login' });
    }
  },
  loader: ({ context }) => {
    // Loader knows user exists (TS infers this!)
    return fetchUserDashboard(context.user.id);
  }
});

The context flows down the tree, and TypeScript knows exactly what's available at each level. If a parent adds user, every descendant route can access it with full type safety.

Key Takeaway: Use route context to share typed data across your route tree and beforeLoad to enforce authentication checks or prerequisites before rendering, ensuring both runtime safety and type-level guarantees.