When working with JWT in Node.js, token expiry does not automatically log the user out on the frontend. The behavior depends on how you handle it.
What happens when JWT expires?
- The token still exists in browser storage (localStorage / cookies)
- But it becomes invalid
- Any API request using that token will fail with 401 Unauthorized
So technically:
👉 User is not logged out automatically, but
👉 User is treated as unauthenticated by the server
How to check token expiry?
1. Server-side (Recommended & Secure)
JWT already contains an exp field (expiry time).
When you verify the token, Node.js automatically checks it.
const jwt = require("jsonwebtoken");
try {
const decoded = jwt.verify(token, "secretKey");
} catch (err) {
// Token expired or invalid
return res.status(401).send("Token expired");
}
If expired → it throws an error → you handle logout on frontend.
2. Frontend (Optional Check)
You can decode the token and check expiry manually.
const token = localStorage.getItem("token");
const decoded = JSON.parse(atob(token.split(".")[1]));
if (decoded.exp * 1000 < Date.now()) {
console.log("Token expired");
}
This helps in:
- Auto logout UI
- Preventing unnecessary API calls
Best Practice (Real-world flow)
- User logs in → token stored
- Every API request → token sent
- If token expired:
- Backend returns 401 Unauthorized
- Frontend catches it
- Clears token
- Redirects to login page
Better Approach: Refresh Tokens
Instead of logging out immediately, many apps use:
- Access Token (short expiry) → e.g. 15 min
- Refresh Token (long expiry) → e.g. 7 days
Flow:
- Access token expires
- Frontend calls refresh API
- New access token generated
- User stays logged in
Important Notes
- Never trust frontend-only expiry checks (can be manipulated)
- Always validate token on backend
- Prefer httpOnly cookies over localStorage for security
Key Takeaway
JWT expiry does not automatically log out the user, but once expired, the server rejects requests. Proper handling involves detecting 401 responses, clearing the token, and optionally using refresh tokens for seamless user experience.