Skip to main content

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 the headers 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 the headers 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:
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

  1. Use httpOnly for sensitive cookies - Prevents XSS attacks
  2. Always use secure in production - Ensures HTTPS-only transmission
  3. Set appropriate SameSite - Protects against CSRF attacks
  4. Sign sensitive cookies - Prevents tampering
  5. Set reasonable expiration - Balance convenience and security
  6. Use Cache-Control wisely - Improve performance without serving stale data
  7. Handle CORS properly - Allow legitimate cross-origin requests while maintaining security
  8. Rotate cookie secrets - Keep multiple secrets for zero-downtime rotation