Skip to main content

Command Palette

Search for a command to run...

36. Local Storage | Session Storage | Cookies

This article will talk about local storage, session storage and cookies in browser.

Updated
โ€ข5 min read
S
Full-Stack Developer with 4 years' experience, specializing in backend development. Skilled in JavaScript, React, Python, Databases, and AWS. Known for building scalable web apps, leading teams, and maintaining strong client communication. Upskilling in Generative AI.

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
๐Ÿ’ก
Both 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";
๐Ÿ’ก
An assignment to 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.

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
*/

Cookies can be:

  1. Session Cookies

    • deleted when browser closes
  2. 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:-

๐Ÿ’ก
Among local storage, session storage and cookies, cookies have the least storage size (~ 4KB). This is because, data stored in cookies get automatically sent to the server with each request.
๐Ÿ’ก
Total number of cookies per domain is limited to around 20+ (browser dependent).

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!