Headers and Cookies
Learn how to work with HTTP headers and cookies in React Router applications.Overview
React Router provides APIs for managing HTTP headers through theheaders export and cookies through the Cookie API. These work seamlessly with loaders, actions, and middleware.
Reading Headers
Access request headers in loaders and actions:Setting Response Headers
Return custom headers from loaders and actions:Headers Function
Use theheaders export for advanced header management:
Working with Cookies
Create and manage cookies using the Cookie API:Reading Cookies
Parse cookies in loaders and actions:Setting Cookies
Set cookies in action responses:Signed Cookies
Sign cookies to prevent tampering:Multiple Cookies
Set multiple cookies in one response:Deleting Cookies
Expire cookies to delete them:Cookie Options
Available cookie options:Cache Control Headers
Manage caching with appropriate headers:CORS Headers
Handle cross-origin requests:Custom Headers Function
Merge headers from multiple sources:Best Practices
- Use httpOnly for sensitive cookies - Prevents XSS attacks
- Always use secure in production - Ensures HTTPS-only transmission
- Set appropriate SameSite - Protects against CSRF attacks
- Sign sensitive cookies - Prevents tampering
- Set reasonable expiration - Balance convenience and security
- Use Cache-Control wisely - Improve performance without serving stale data
- Handle CORS properly - Allow legitimate cross-origin requests while maintaining security
- Rotate cookie secrets - Keep multiple secrets for zero-downtime rotation