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
Use pathless layout routes
Use pathless layout routes
Wrap protected routes in
_authenticated layout for clean URLs.Check auth in beforeLoad
Check auth in beforeLoad
Use
beforeLoad instead of loader for auth checks to avoid data fetching for unauthorized users.Store minimal data in context
Store minimal data in context
Only store essential auth state - fetch user details when needed.
Handle token expiration
Handle token expiration
Implement token refresh logic and redirect to login on expiration.
Use HTTPS in production
Use HTTPS in production
Always use HTTPS to protect authentication tokens and credentials.
Security considerations
Implement CSRF protection for state-changing operations.
Next steps
Data loading
Load user data in protected routes
beforeLoad hook
Learn more about beforeLoad