Skip to main content

Command Palette

Search for a command to run...

1) Authentication JWT flow

Updated
View as Markdown
  1. JWT (JSON Web Token) authentication in a React app isn’t actually handled by React itself—it’s a flow between your frontend (React), backend (Node/Express, etc.), and the browser. React’s role is mainly storing and sending the token.
    i) User Logs In
    User enters email/password in a React form and React sends a request to backend

    POST /api/login
    {
      email,
      password
    }
    

    ii) Backend Validates & Creates JWT token
    Server checks credentials (DB lookup, password hash compare)
    If valid, it generates a JWT using something like: payload (userId, role, etc.), secret key and expiry time.
    iii) React Stores the Token
    Common storage options: LocalStorage (simple, but less secure), SessionStorage HTTP-only cookies (most secure, recommended in production)

    localStorage.setItem("token", response.token);
    

    iv) React Sends Token in Requests
    For protected APIs, React includes the JWT in headers

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

    v) Backend Middleware Verifies JWT
    Every protected route has middleware

    const token = req.headers.authorization?.split(" ")[1];
    
    jwt.verify(token, SECRET_KEY);
    

    If valid: Request proceeds User info is attached to req.user
    If invalid: Return 401 Unauthorized
    vi) Token Expiry & Refresh Flow
    JWTs usually expire (e.g., 15 min).
    Two approaches:
    Basic - User logs in again after expiry
    Advanced (Production) - Use Refresh Tokens
    Short-lived access token
    Long-lived refresh token
    Backend issues new token without re-login
    vi) Logout Flow
    React removes token

    localStorage.removeItem("token");
    
  2. Protected routes
    Protected routes in React are how you restrict access to certain pages unless the user is authenticated (and optionally authorized). They’re implemented at the routing layer—typically using React Router.
    Before rendering this page, check if the user is logged in. If not, redirect to different page.
    i) ProtectedRoute Component

    import { Navigate } from "react-router-dom";
    
    const ProtectedRoute = ({ children }) => {
      const token = localStorage.getItem("token");
    
      if (!token) {
        return <Navigate to="/login" replace />;
      }
    
      return children;
    };
    
    export default ProtectedRoute;
    

    ii) Usage in Routes

    import { BrowserRouter, Routes, Route } from "react-router-dom";
    import ProtectedRoute from "./ProtectedRoute";
    
    <BrowserRouter>
      <Routes>
        <Route path="/login" element={<Login />} />
    
        <Route
          path="/dashboard"
          element={
            <ProtectedRoute>
              <Dashboard />
            </ProtectedRoute>
          }
        />
      </Routes>
    </BrowserRouter>