
Dec 30, 2024 • By Sohan Paliyal
Modern web applications need to maintain state and session continuity to provide a seamless user experience. To manage this "auth state," browsers provide three main storage mechanisms: localStorage, sessionStorage, and Cookies.
In this article, we will decode these storage layers, explore how we built a "Remember Me" feature, and discuss interesting browser behaviors regarding session restoration.
localStorage is a mechanism for storing key-value pairs in a web browser with no expiration time.
localStorage.setItem("remember_me", "true"); // Persists until cleared
sessionStorage allows you to access a storage area that's unique to a specific browser session.
sessionStorage.setItem("step", "2"); // Available for the duration of the page session
Cookies are small blocks of data created by a web server while a user is browsing a website and placed on the user's computer or other device by the user's web browser.
HttpOnly (inaccessible to JavaScript), Secure (HTTPS only), and SameSite (CSRF protection).Set-Cookie: session_id=abc123; HttpOnly; Secure
We implemented a specific behavior for our authentication flow:
We combined two mechanisms:
localStorage — Indicates user intent for persistence.localStorage.setItem("remember_me", "false"); // Stores user preference
document.cookie = "active_session=true; path=/"; // Sets the session cookie
const rememberMe = localStorage.getItem("remember_me");
const hasSessionCookie = document.cookie.includes("active_session=true");
if (rememberMe !== "true" && !hasSessionCookie) {
logoutUser(); // Clears session if specific criteria aren't met
}
Logic: If the user did not opt for "Remember Me" AND the session cookie is missing (indicating a fresh browser session), the application logs the user out.
Browsers typically clear session cookies when the application closes, handling the cleanup automatically.
An interesting edge case arises with the "Restore Closed Tab" feature found in modern browsers.
If a user unchecks "Remember Me", closes the browser, and then uses Cmd + Shift + T (or Ctrl + Shift + T) to restore the tab, they will often find themselves still logged in.
Modern browsers treat "Tab Restore" as a continuation of the previous session rather than a fresh start.
No, this is intended behavior. GitLab and other major platforms document this: "Session restoration is considered a trusted continuity signal."
Forcing a logout in this scenario would disrupt the user experience, as the user explicitly requested to restore their previous state.
Yes.
Understanding these storage nuances helps in designing robust authentication flows and state management systems.
Happy Coding! 🚀