Browse documentation
Lesson 14 · Authenticated routes

Confirm identity before child routes load

Protect a route group with typed Router Context and a pathless layout beforeLoad while preserving the correct post-login destination.

TanStack RouterIntermediate22 minREV 01Markdown .md
After this lesson

Build an auth gate that stops private child routes before loading and explain why it still cannot replace server authorization.

01

Identity, permission, and navigation are different concerns

Authentication answers who the user is, authorization answers whether that user may access a resource, and a Router gate only owns navigation UX. beforeLoad can stop child loading and redirect to login, but every server entry that reads or mutates private data must authenticate again and enforce resource-level authorization.

02

Centralize the gate in a pathless layout

A parent beforeLoad runs before its children, so grouping private pages under `_authenticated` reuses one check. Preserve the actual destination from the callback location.href instead of a potentially stale resolvedLocation. The login page must validate that the destination is local to prevent open redirects.

src/routes/_authenticated.tsxtsx
import { Outlet, createFileRoute, redirect } from '@tanstack/react-router'

export const Route = createFileRoute('/_authenticated')({
  beforeLoad: ({ context, location }) => {
    if (!context.auth.user) {
      throw redirect({
        to: '/login',
        search: { redirect: location.href },
      })
    }

    return { user: context.auth.user }
  },
  component: () => <Outlet />,
})
03

Separate auth failures from signed-out state

A missing session can redirect predictably, while an auth-service timeout, network failure, or configuration error belongs to observable error recovery. If auth errors are caught, Router redirects must be rethrown rather than swallowed as ordinary failures.

PRACTICE

Turn this lesson into a verifiable skill

Completion checkpoint

A signed-out user redirects before any private child loader runs, while a signed-in user receives a typed user from context.

Exercise

Create an `_authenticated` pathless layout for dashboard and settings, then return safely to the original same-origin URL after login.

Verification

Test signed-out direct entry, signed-in refresh, session expiry, and a malicious external redirect; the server endpoint must independently reject unauthorized requests.

Common pitfalls
  • Hiding navigation links while private loaders and server endpoints remain callable.
  • Navigating to an unchecked redirect parameter and creating an open redirect.
SOURCE REFERENCES · CHECKED 2026-08-03https://tanstack.com/router/latest/docs/framework/react/guide/authenticated-routeshttps://tanstack.com/router/latest/docs/framework/react/guide/router-context
TanStack Atlas

Original bilingual knowledge · verified against primary sources

Friend linksGitHub