Skip to main content
Implement authentication flows with protected routes, redirects, and context-based access control.

Setup auth context

Create an authentication context for your router:
src/auth.tsx

Router with auth context

Provide auth context to all routes:
src/main.tsx

Protected routes

Guard routes with authentication checks:
src/routes/_authenticated.tsx

Login page

Implement login with redirect:
src/routes/login.tsx

Role-based access

Protect routes based on user roles:
src/routes/_authenticated/_admin.tsx

Conditional navigation

Show links based on permissions:

Session management

Check and refresh authentication:
src/routes/__root.tsx

Token-based auth

Store and use JWT tokens:
src/auth.tsx

OAuth/Social login

Implement OAuth flows:
src/routes/auth/callback.tsx

Logout handling

Clear session and redirect:

Persisting auth state

Restore auth on page reload:
src/main.tsx

Best practices

Wrap protected routes in _authenticated layout for clean URLs.
Use beforeLoad instead of loader for auth checks to avoid data fetching for unauthorized users.
Only store essential auth state - fetch user details when needed.
Implement token refresh logic and redirect to login on expiration.
Always use HTTPS to protect authentication tokens and credentials.

Security considerations

Never store sensitive data like passwords in localStorage. Use secure, httpOnly cookies for tokens when possible.
Always validate user permissions on the server. Client-side checks are for UX only.
Implement CSRF protection for state-changing operations.

Next steps

Data loading

Load user data in protected routes

beforeLoad hook

Learn more about beforeLoad