Introduction
As a frontend developer, there are several browser storage solutions you must know, with key differences in: capacity limits, expiration settings, and whether they interact with the server, each having distinct characteristics suitable for different scenarios.
Cookie
Cookies are the earliest browser-side storage mechanism, with the main feature being their automatic inclusion in each HTTP request, enabling state synchronization between the user and the server. This characteristic is particularly suitable for maintaining states and server-side user identification.
You can set max-age
or expires
for a cookie to control its expiration, as well as attributes like HttpOnly
and Secure
to enhance security. However, since cookies are attached to every request, misuse can impact network performance.
Browser Document.cookie
setting:
document.cookie = newCookie;
Setting via server HTTP header Set-Cookie
:
Set-Cookie: <cookie-name>=<cookie-value>Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date>Set-Cookie: <cookie-name>=<cookie-value>; HttpOnlySet-Cookie: <cookie-name>=<cookie-value>; Max-Age=<number>Set-Cookie: <cookie-name>=<cookie-value>; PartitionedSet-Cookie: <cookie-name>=<cookie-value>; Path=<path-value>Set-Cookie: <cookie-name>=<cookie-value>; Secure
Set-Cookie: <cookie-name>=<cookie-value>; SameSite=StrictSet-Cookie: <cookie-name>=<cookie-value>; SameSite=LaxSet-Cookie: <cookie-name>=<cookie-value>; SameSite=None; Secure
// Multiple attributes are also possible, for example:Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure; HttpOnly
LocalStorage
localStorage does not send data with requests to the server and can retain data permanently until explicitly removed. Compared to cookies, localStorage has a larger capacity and is more suitable for storing user preferences or profiles.
localStorage.setItem("name", "Joe");localStorage.getItem("name");
SessionStorage
sessionStorage
is similar to localStorage
, but its main difference is that its lifespan is limited to the current “tab session” Once the browser tab is closed, the stored content is cleared.
sessionStorage.setItem("name", "Joe");sessionStorage.getItem("name");
Extended Topics
Data Structures Beyond Strings
cookie
, localStorage
, and sessionStorage
all store data in “key-value” pairs, and the “value can only be a string.” To store objects or arrays, you must use JSON.stringify()
to convert them to strings before storing and then parse them back with JSON.parse()
:
const user = { name: 'Alice', age: 30 };localStorage.setItem('user', JSON.stringify(user));
const data = JSON.parse(localStorage.getItem('user'));
Cookies and Regulations
If the website targets international users, it is advisable to refer to GDPR (General Data Protection Regulation)
- Scope: Users within the EU, even if the website is not in the EU, as long as it serves EU users.
- Key Regulations:
- Explicit prior consent: Non-essential cookies (like tracking, advertising) must not be pre-activated and must require user “active opt-in.”
- Cookie policy explanation: Must clearly state the purpose of cookies, storage time, and third-party sharing scenarios.
- Right to withdraw: Users should be able to modify or withdraw cookie consent at any time.
This is also why many websites ask for permission before using cookies, concerning personal data protection regulations.
Cookie Security Enhancement
- Secure: Ensure that it is only sent to the server when the request is encrypted via the HTTPS protocol.
- HttpOnly: Prevents the JavaScript
Document.cookie
method from accessing HttpOnly cookies; HttpOnly cookies are only sent to the server, protecting against cross-site scripting (XSS) attacks.
Summary
Item | Cookie | localStorage | sessionStorage |
---|---|---|---|
Capacity Limit | About 4KB | About 5~10 MB | About 5~10 MB |
Expiration | Expiration time can be set | Permanent until manually deleted | Until the tab is closed |
Interaction with Server | Automatically sent with each request | None | None |
Common Uses | Store information interacting with server (login states, language preferences, etc.) | Store local data (Client-Side shopping cart list, offline data) | Store single tab data (single login process, form data temporarily saved) |