Browser Storage Explained: LocalStorage, SessionStorage and Cookies
Quick Answer: Browser storage helps websites remember information between visits and page changes. LocalStorage keeps data until it is cleared. SessionStorage keeps data for one browser tab session. Cookies can store small values and send matching cookies with HTTP requests. Choose storage based on data lifetime, server needs and security.
1. Why Do Websites Need Browser Storage?
Imagine you manage an online grocery shop with thousands of customers.
A customer adds rice, milk and vegetables to their shopping cart. They open another page. Should the cart become empty?
Think about the same customer returning tomorrow. Should the website remember their selected preferences?
Web pages do not automatically remember every value after navigation or reload. We need a way to store selected information.
The problem without browser storage
Consider a simple shopping cart. It stores products inside a JavaScript variable.
Example 1: Shopping cart without browser storage
This code stores cart items only in the current page memory.
const cart = [];
cart.push("Rice");
cart.push("Milk");
cart.push("Vegetables");
console.log("Shopping cart:", cart);
console.log("Total items:", cart.length);
Expected output
Shopping cart: [ "Rice", "Milk", "Vegetables" ] Total items: 3
This works, but the data exists only in page memory.
What happens when the customer reloads the page?
- The JavaScript page starts again.
- The cart variable gets created again.
- The previous cart items are lost.
- The customer must add those products again.
Now think about thousands of customers using the same website. Losing useful cart information creates a poor experience.
How browser storage solves this problem
Browser storage saves selected information outside the current JavaScript page memory. The browser can read that information again when needed.
| Situation | Without storage | With storage |
|---|---|---|
| Page reload | In-memory cart is lost. | Saved cart can be loaded again. |
| New page | New page starts with fresh variables. | Pages can read shared saved data. |
| New tab | Page memory is separate. | LocalStorage can be shared across same-origin tabs. |
| Server request | No automatic cart cookie exists. | Matching cookies can be sent automatically. |
Terms to remember:
- Browser storage = a place where the browser keeps website data.
- LocalStorage = storage that normally remains after closing the browser.
- SessionStorage = storage linked to one page's tab session.
- Cookie = a small value stored by the browser and shared with matching requests.
- Origin = the combination of protocol, hostname and port.
- Serialization = converting data into a format that can be stored as text.
2. Understand the Three Browser Storage Options
All three options can remember information. Their lifetimes and server behaviour differ.
2.1 LocalStorage
LocalStorage keeps data for a website origin. Closing the tab does not normally remove it.
Use it for information that should remain on the device. Examples include display preferences and a non-sensitive shopping cart.
Example 2: Save and read a shopping cart
Open the browser developer console on your website and run this code.
const cart = [
"Rice",
"Milk",
"Vegetables"
];
localStorage.setItem(
"shoppingCart",
JSON.stringify(cart)
);
const savedCart = JSON.parse(
localStorage.getItem("shoppingCart") || "[]"
);
console.log(savedCart);
console.log("Total items:", savedCart.length);
Expected output
[ "Rice", "Milk", "Vegetables" ] Total items: 3
LocalStorage stores strings, not JavaScript objects. We use JSON.stringify to convert the array into text.
JSON.parse converts that text back into a JavaScript value.
2.2 SessionStorage
SessionStorage keeps data for a particular page session in a tab. Reloading the page does not normally clear it. Closing that tab ends its session.
Use it for temporary information. Examples include a checkout step or temporary form progress.
Example 3: Save the current checkout step
sessionStorage.setItem("checkoutStep", "payment");
const currentStep = sessionStorage.getItem("checkoutStep");
console.log("Current checkout step:", currentStep);
Expected output
Current checkout step: payment
The value remains available after a reload in that tab. Another tab has its own sessionStorage area.
Important: A newly opened tab may receive an initial copy when it has an opener. After that, the two sessionStorage areas are separate.
2.3 Cookies
Cookies store small pieces of data for a website. The browser can send matching cookies with HTTP requests.
Use cookies when the server needs a value on later requests. Common examples include session identifiers and server-managed preferences.
Example 4: Create and read a simple cookie
// Store a cookie for the current site path.
document.cookie = "shopView=grid; max-age=3600; path=/";
// Read the cookies visible to JavaScript.
console.log(document.cookie);
Example output
shopView=grid
The max-age value is measured in seconds. Here, the cookie can live for one hour.
The path attribute controls which URL paths receive the cookie. The root path makes it available across the site's paths.
Security note: JavaScript-created cookies cannot use the HttpOnly flag. A server must set HttpOnly when JavaScript should not read the cookie.
3. Visual Guide: Where Does Each Storage Type Fit?
The following diagram uses a grocery shopping cart as its example. Each storage type has a different purpose.
Animation 1: Choose storage by its purpose
The highlighted stages show how the website chooses storage based on the information's purpose.
4. Compare LocalStorage, SessionStorage and Cookies
| Feature | LocalStorage | SessionStorage | Cookies |
|---|---|---|---|
| Lifetime | Until cleared or removed | Until the tab session ends | Session or configured expiry |
| Storage format | Strings | Strings | Name-value pairs |
| Typical size | Browser-dependent quota | Browser-dependent quota | Small; commonly around 4 KB per cookie |
| Sent with HTTP requests | No | No | Yes, when cookie rules match |
| JavaScript access | Yes, for same origin | Yes, for same origin | Unless HttpOnly is set |
| Scope | Origin | Origin and tab session | Domain, path and other cookie rules |
| Best use | Persistent preferences | Temporary page-session data | Server session and request-related data |
Cookie limits and browser storage quotas vary by browser. Do not design your application around one fixed quota.
Visualise how long the data remains
Animation 2: Storage lifetime comparison
The three animated indicators represent different lifetimes, not measured time or storage capacity.
5. How Browser Storage Works During HTTP Requests
LocalStorage and SessionStorage stay inside the browser. They are not automatically attached to HTTP requests.
Cookies behave differently. The browser can attach matching cookies to requests sent to a server.
Animation 3: Browser to server request flow
This diagram separates browser-only storage from cookies that can travel with matching requests.
Important cookie attributes
- Expires: Sets a date when the cookie should expire.
- Max-Age: Sets how many seconds the cookie should remain valid.
- Path: Limits the URL paths that receive the cookie.
- Domain: Controls which hostnames can receive the cookie.
- Secure: Sends the cookie only over secure HTTPS connections.
- HttpOnly: Prevents JavaScript from reading the cookie.
- SameSite: Controls when cookies are sent with cross-site requests.
SameSite values include Strict, Lax and None. None requires Secure in modern browsers.
6. Build a Practical Shopping Cart with LocalStorage
Let's create a small cart for a grocery shop. It will save products between page reloads.
The example uses a browser page with a JavaScript console. It does not need an external library.
Step 1: Create a cart storage helper
Example 5: Save, load and clear cart data
const CART_KEY = "upgradixShoppingCart";
function loadCart() {
try {
const savedValue = localStorage.getItem(CART_KEY);
return savedValue ? JSON.parse(savedValue) : [];
} catch (error) {
console.error("Could not read the cart.", error);
return [];
}
}
function saveCart(cart) {
localStorage.setItem(CART_KEY, JSON.stringify(cart));
}
function addProduct(productName) {
const cart = loadCart();
cart.push(productName);
saveCart(cart);
console.log("Added:", productName);
}
function showCart() {
console.log("Saved cart:", loadCart());
}
function clearCart() {
localStorage.removeItem(CART_KEY);
console.log("Cart cleared.");
}
addProduct("Rice");
addProduct("Milk");
addProduct("Vegetables");
showCart();
Expected output
Added: Rice Added: Milk Added: Vegetables Saved cart: [ "Rice", "Milk", "Vegetables" ]
Step 2: Understand the implementation
CART_KEYgives the saved value a consistent key.loadCart()reads the saved text and converts it into an array.saveCart()converts the array into text before saving.addProduct()loads the existing cart before adding a product.removeItem()is not needed to remove one product; use an updated array and save it again.clearCart()removes only this cart entry.
Try it: Run the example, reload the page and call showCart() again. The saved items should still appear for the same origin.
7. Cookies in Practice: Safer Server-Managed Sessions
Cookies are often useful when a server needs to recognise a browser session.
For authentication, prefer a server-managed session cookie with suitable security attributes. Do not store sensitive session credentials in JavaScript-readable storage.
Example 6: Set a secure session cookie from a server
This is an illustrative HTTP response header. The server creates the cookie.
Set-Cookie: __Host-shopSession=opaque-session-id; Path=/; Secure; HttpOnly; SameSite=Lax
The browser stores this cookie and sends it with matching requests. JavaScript cannot read its value because HttpOnly is set.
The server must still validate the session identifier. Cookie attributes do not replace server-side access checks.
Important: Cookies are automatically attached to eligible requests. This can create cross-site request risks. Protect state-changing requests with suitable CSRF defences and an appropriate SameSite policy.
8. Common Browser Storage Mistakes
Mistake 1: Saving an object directly
Storage methods expect strings. Passing an object directly does not save its structure.
Wrong:
localStorage.setItem("cart", { product: "Rice" });
Correct:
localStorage.setItem(
"cart",
JSON.stringify({ product: "Rice" })
);
Mistake 2: Parsing missing or invalid data
getItem() returns null when the key does not exist. Invalid JSON can also throw an error.
Check the value and handle parsing errors. Do not assume stored data is always valid.
Mistake 3: Storing sensitive information in LocalStorage
JavaScript running on the same origin can read LocalStorage. A successful cross-site scripting attack may expose its contents.
Do not store passwords, private keys or session secrets there. Prefer secure, HttpOnly cookies for server-managed sessions.
Mistake 4: Expecting storage to sync automatically
Changing LocalStorage in one tab does not update every JavaScript variable in other tabs.
The browser provides a storage event for changes made in another document. The document that made the change does not receive that event.
Example 7: Listen for changes from another tab
window.addEventListener("storage", (event) => {
if (event.key === "upgradixShoppingCart") {
console.log("Cart changed in another tab.");
console.log("New value:", event.newValue);
}
});
Expected console message when another tab changes the cart
Cart changed in another tab. New value: ["Rice","Milk"]
Mistake 5: Treating browser storage as a database
Browser storage belongs to one browser profile and origin. It is not a shared database for all customers.
Do not use it as the source of truth for payments, stock or order totals. The server must verify important business data.
9. Best Practices for Production Applications
- Store only the data your application really needs.
- Use LocalStorage for non-sensitive preferences that should persist.
- Use SessionStorage for temporary, tab-specific information.
- Use cookies when the server needs browser information on requests.
- Use HttpOnly and Secure for sensitive server-managed session cookies.
- Choose a suitable SameSite policy and protect state-changing requests.
- Handle missing, expired and invalid stored values.
- Expect storage operations to fail in restricted browser environments.
- Do not trust browser values for prices, permissions or payment status.
- Clear data when users sign out, where your application design requires it.
- Remember that users and browser settings can clear stored information.
What about performance and scale?
LocalStorage and SessionStorage are synchronous APIs. Reading and writing them can block JavaScript while the operation runs.
Keep stored values small. Avoid frequent large reads and writes during busy page interactions.
For larger structured browser data, consider IndexedDB. It offers asynchronous access and supports more complex data.
Cookies are included in matching HTTP requests. Keep them small because they add request data.
10. How This Topic Appears in Interviews
Question 1: What is the difference between LocalStorage and SessionStorage?
What the interviewer wants: They want to check lifetime and scope.
Strong answer: "LocalStorage keeps data for an origin until it is cleared. SessionStorage keeps data for a particular tab session. Both store strings and are not sent automatically with HTTP requests."
Question 2: Why are cookies different from LocalStorage?
Strong answer: "Cookies can be sent automatically with matching HTTP requests. LocalStorage stays in the browser and is not sent automatically. Cookies also support attributes such as HttpOnly, Secure and SameSite."
Question 3: Where would you store an authentication session?
Strong answer: "I would prefer a server-managed session cookie. I would set HttpOnly, Secure and a suitable SameSite policy. I would also protect state-changing requests and validate the session on the server."
Question 4: Can LocalStorage be shared between tabs?
Strong answer: "Tabs from the same origin can access the same LocalStorage area. Changes can notify other documents through the storage event. SessionStorage is separate for each tab session."
What should different experience levels explain?
- Junior: Explain the three storage types and their basic APIs.
- Senior: Explain expiry, error handling, cross-tab changes and security.
- Architect: Explain session design, CSRF protection, XSS risks and server responsibilities.
11. Hands-On Practice
Beginner: Save a display preference
Save the customer's preferred product display mode using LocalStorage.
- Save either grid or list as the selected value.
- Read the value when the page loads.
- Use grid when no saved value exists.
Expected result: The selected display mode remains after a page reload.
Intermediate: Build a temporary checkout
Use SessionStorage to remember the current checkout step.
- Save the current step after each action.
- Restore the step after a page reload.
- Test the same page in another tab.
Expected result: Each tab maintains its own checkout progress.
Advanced: Create a server session cookie
Create a server endpoint that sets a session cookie. Use HttpOnly, Secure and a suitable SameSite value.
- Read the cookie on the server.
- Validate the session identifier.
- Test requests from another site.
- Add suitable CSRF protection.
Expected result: The server recognises valid sessions without exposing the cookie to JavaScript.
12. Frequently Asked Questions
Does LocalStorage remain after closing the browser?
Normally, yes. It remains until the user or application clears it. Browser privacy settings can affect this behaviour.
Does SessionStorage survive a page reload?
Yes. It normally survives reloads in the same tab session. Closing the tab ends that session.
Are cookies more secure than LocalStorage?
Not automatically. HttpOnly prevents JavaScript access to a cookie. Secure and SameSite add other protections. Correct server-side session handling remains important.
Can I store an array in LocalStorage?
Yes. Convert it to JSON text with JSON.stringify. Read it back with JSON.parse and handle invalid data.
Are LocalStorage values shared between websites?
No. LocalStorage is separated by origin. Different protocols, hostnames or ports have different origins.
Should I use LocalStorage for access tokens?
Be careful. JavaScript can read LocalStorage values. An XSS vulnerability can expose them. Consider a secure server-managed session design instead.
13. Next Steps and Community
You now understand how browsers store website information. You also know when each storage option makes sense.
Try It Yourself: Build the grocery cart example and test it across page reloads and tabs.
Explore Further: Read the official documentation for LocalStorage, SessionStorage and HTTP Cookies.
Share Your Knowledge: Share your implementation and discuss other storage choices. Help other developers understand the trade-offs.
Choose browser storage based on lifetime, security and server requirements.