SmartCodingTips

πŸ” Auth Tokens in React

Auth tokens, like JWT (JSON Web Tokens), are commonly used to manage user authentication in React apps. They are passed with each request to validate the user’s session.


🧾 1. What Is an Auth Token?

  • A token is a string (usually JWT) issued by the server after login
  • Includes user data, expiry, and signature
  • Used to validate requests without needing credentials every time

πŸ“¦ 2. Where to Store Tokens?

  • LocalStorage: Simple, persists across tabs, but vulnerable to XSS
  • SessionStorage: Clears on tab close, but also XSS-vulnerable
  • HTTP-only cookies: Most secure (can't be accessed via JavaScript)

πŸ”§ 3. Sending Tokens with Requests

Include the token in the Authorization header of API calls:


const token = localStorage.getItem('authToken');

fetch('/api/user', {
  headers: {
    Authorization: `Bearer ${token}`
  }
});

πŸ”„ 4. Persisting Auth State

  • Use useEffect to check for token on app load
  • Store token in context or Redux after login
  • Clear token on logout

⏳ 5. Token Expiry & Refresh

  • Tokens usually have an expiry time (e.g., 15 min)
  • Use refresh tokens (stored in HTTP-only cookies) to silently renew access tokens
  • Log user out if token is invalid or expired

πŸ“‹ Summary

  • Use tokens to authenticate users in your React app
  • Store securely: prefer HTTP-only cookies over localStorage
  • Always include tokens in request headers for protected APIs
  • Implement refresh logic or force logout on expiry