36. Local Storage | Session Storage | Cookies
This article will talk about local storage, session storage and cookies in browser.
Local Storage
Methods provided by local storage:-
localStorage.setItem(key, value) // store key-value pair
localStorage.getItem(key) // get the value by key
localStorage.removeItem(key) // removes the key-value pair
localStorage.clear() // clears the local storage
localStorage.key(index) // get the key on the given position
localStorage.length // returns the number of stored items
key and value must be string.Session Storage
Properties and methods are same as local storage.
sessionStorage.setItem(key, value) // store key-value pair
sessionStorage.getItem(key) // get the value by key
sessionStorage.removeItem(key) // removes the key-value pair
sessionStorage.clear() // clears the session storage
sessionStorage.key(index) // get the key on the given position
sessionStorage.length // returns the number of stored items
Cookies
Cookies are small pieces of data stored in user's browser.
They are mainly used to remember information about the user between requests.
How to set cookies?
Option 1 (Frontend): Using JavaScript
In javascript, document.cookie provides access to cookies.
document.cookie = "theme=dark; loggedIn=true; expires=1 Jan 1970";
document.cookie is treated specially in a way that a write operation doesn't touch other cookies.document.cookie = "user=shubham";
// updates only cookie named user to shubham
Option 2 (Backend): Via Web Server
Using Set-Cookie HTTP response header.
Next time when the request is sent to the same domain, the browser sends the cookie using the Cookie HTTP request header. That way the server knows who sent the request.
Cookie Options
Cookies have several options which can be provided after key=value pair.
document.cookie = "user=abc; sessionId=123; path=/xyz; expires=Tue, 29 March 2029; HttpOnly; Secure; SameSite=Lax";
/* Here following are the cookie options:-
- path
- expires
- HttpOnly
- Secure
- SameSite
*/
Cookie Lifetime
Cookies can be:
Session Cookies
- deleted when browser closes
Persistent Cookies
- survive until expiration date
Security Level
Cookies become significantly safer when configured with:
| Flag | Purpose |
|---|---|
HttpOnly |
Prevents JS access. |
Secure |
Stored and sent only over HTTPS connections. |
SameSite |
Helps prevent CSRF attacks. It controls whether cookies are sent automatically with requests initiated by third-party websites. Value can be Strict, Lax or None. |
document.cookie = "sessionToken=abc123xyz; HttpOnly; SameSite=Lax; Secure";
Note:-
Comparison
| Local Storage | Session Storage | Cookies | |
|---|---|---|---|
| Storage Location | Browser | Browser | Browser |
| Size Limit | ~ 5-10 MB | ~ 5 MB | ~ 4 KB |
| Sent to server automatically? | โ No | โ No | โ Yes |
| Accessible by JavaScript? | โ Yes | โ Yes | โ Yes |
โ No, if HttpOnly |
|||
| Security Level | Low (XSS risk) | Medium | High (when configured with HttpOnly, Secure & SameSite) |
| Performance Impact | Fast | Fast | Slightly slower |
| Survives Page Refresh? | โ Yes | โ Yes | โ Yes |
| โญ Lifetime | Persistent until explicitly deleted by user/app | Exists only for the current browser tab/session. Removed when tab/window closes | Configurable. (can be session-based or persistent depending on Expires / Max-Age) |
| โญ Scope | Shared across all tabs/windows of same origin (protocol + domain + port) | Limited to a single tab. Another tab with same page will have a different session storage. | Sent automatically with every request to matching domain and path |
| Use Case | User preferences; cached UI data | Multi-step forms, temporary tab-specific state | Authentication, session management, tracking |
Extra Notes
encodeURIComponent()
This function helps keep the valid formatting by encoding special characters in a string.
const string = "apples & oranges = tasty!";
const encoded = encodeURIComponent(string);
console.log(encoded);
// Output: apples%20%26%20oranges%20%3D%20tasty%21
decodeURIComponent()
This function reverses the process. It takes an encoded string and changes the percent-encoded sequences back into their original character forms.
const encodedString = "apples%20%26%20oranges%20%3D%20tasty%21";
const decoded = decodeURIComponent(encodedString);
console.log(decoded);
// Output: apples & oranges = tasty!
JSON.stringify(obj)
Converts object to JSON string.
const obj = {name: "shubham", age: 25};
console.log(JSON.stringify(obj));
// Output: '{"name":"shubham","age":25}'
const arr = [1, true, "shubham"]
console.log(JSON.stringify(arr));
// Output: '[1,true,"shubham"]'
JSON.parse(string)
Converts string to object. String must be a valid JSON format.
const str = '{"name":"shubham","age":25}';
console.log(JSON.parse(str));
// Output: {name: "shubham", age: 25}
Happy learning!

