Adding Auto Logout
Auto logout signs a user out automatically when their authentication token expires, so the frontend never keeps showing a "logged in" screen with a token the server will reject. You add it once you are storing the token and its expiry time, usually right after making the login state survive a page refresh.
Why the frontend needs its own timer
Tokens such as JWTs usually carry an expiry. After that moment the backend answers every protected request with a 401 error. If the frontend does nothing, the user keeps clicking around, every request fails, and the interface looks broken. A timer that fires at the exact expiry moment lets the app log out cleanly and send the user back to the login page with a clear message.
Storing the expiry, not just the token
When the login request succeeds, the server typically returns the token and either an absolute expiry time or a lifetime in seconds. Convert it to an absolute timestamp right away and save it next to the token. An absolute time still works after a reload, while a relative lifetime would restart every time the page loads.
import { createContext, useCallback, useEffect, useState } from "react";
export const AuthContext = createContext(null);
let logoutTimer;
export function AuthProvider({ children }) {
const [token, setToken] = useState(null);
const [expiresAt, setExpiresAt] = useState(null);
const logout = useCallback(() => {
setToken(null);
setExpiresAt(null);
localStorage.removeItem("auth");
}, []);
const login = useCallback((newToken, lifetimeSeconds) => {
const expiry = Date.now() + lifetimeSeconds * 1000;
setToken(newToken);
setExpiresAt(expiry);
localStorage.setItem("auth", JSON.stringify({ token: newToken, expiry }));
}, []);
useEffect(() => {
if (token && expiresAt) {
const remaining = expiresAt - Date.now();
logoutTimer = setTimeout(logout, remaining);
} else {
clearTimeout(logoutTimer);
}
return () => clearTimeout(logoutTimer);
}, [token, expiresAt, logout]);
return (
<AuthContext.Provider value={{ token, login, logout }}>
{children}
</AuthContext.Provider>
);
}
How the timer flow works
- On login, the token and absolute expiry are put into state and into
localStorage. - The effect sees a token and calculates how many milliseconds are left.
setTimeoutscheduleslogoutfor that moment.- If the user logs out manually first, the token becomes
null, the cleanup runs and the pending timer is cleared.
On page load, the code that restores the saved session should compare the stored expiry to Date.now(). If the time has already passed, delete the saved data instead of restoring it. Otherwise restore both values and the same effect sets up a timer for whatever time remains.
Mistakes that cause surprise logouts
The most common bug is forgetting to clear the old timer. If a user logs out and logs in again, a stale timer from the first session can fire and log them out of the second one. Clearing the timer in the effect cleanup and whenever the token changes prevents this.
Another frequent error is storing the lifetime ("3600") rather than the absolute time. After a refresh the app thinks the user has a fresh hour, while the server already considers the token expired.
Finally, remember that browsers cap setTimeout delays at roughly 24.8 days (the largest 32-bit signed number of milliseconds). For very long sessions the timer fires immediately, so long-lived tokens should be handled with a refresh flow instead.
Making it friendlier
A hard logout in the middle of typing a long form is frustrating. Many apps show a warning a minute or two before expiry, offering to extend the session by requesting a fresh token. That uses the same idea: a second, earlier timer that opens a dialog.
Takeaway: save an absolute expiry, schedule one timer from it, clear that timer on every logout or token change, and check the expiry before restoring a saved session.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.