Modern websites do much more than simply display information. They remember user preferences, maintain login sessions, store shopping cart items, and save application settings.
For example:
Remembering a user's dark mode preference
Keeping products in a shopping cart
Maintaining login sessions
Saving language settings
Tracking website visits
To achieve this, browsers provide storage mechanisms such as:
Local Storage
Session Storage
Cookies
These technologies allow websites to store data directly inside the user's browser.
In this article, we will learn:
What browser storage is
Local Storage
Session Storage
Cookies
Differences between them
Practical examples
Real-world applications
What is Browser Storage?
Browser storage allows websites to save data directly in the user's browser.
Without browser storage:
Refresh Page
↓
Data Lost
With browser storage:
Refresh Page
↓
Data Remains Available
This improves user experience and reduces server requests.
Why Browser Storage is Needed
Imagine an online shopping website.
Without storage:
Add Product to Cart
↓
Refresh Page
↓
Cart Becomes Empty
This would frustrate users.
With storage:
Add Product to Cart
↓
Refresh Page
↓
Cart Still Available
This creates a much better experience.
Types of Browser Storage
JavaScript provides three main storage mechanisms:
| Storage Type | Purpose |
|---|---|
| Local Storage | Permanent browser storage |
| Session Storage | Temporary session storage |
| Cookies | Small data sent to server |
What is Local Storage?
Local Storage stores data permanently in the browser.
Data remains available even after:
Refreshing the page
Closing the browser
Restarting the computer
The data remains until it is manually removed.
Local Storage Characteristics
Stores data permanently
Larger storage capacity
Client-side storage
Easy to use
Storing Data in Local Storage
Syntax:
localStorage.setItem(key, value);
Example:
localStorage.setItem("name", "Rahul");
The value is stored in the browser.
Retrieving Data
Syntax:
localStorage.getItem(key);
Example:
let name = localStorage.getItem("name");
console.log(name);
Output:
Rahul
Updating Data
Example:
localStorage.setItem("name", "Amit");
The previous value is replaced.
Removing Data
Syntax:
localStorage.removeItem(key);
Example:
localStorage.removeItem("name");
The stored value is deleted.
Clearing All Local Storage
Syntax:
localStorage.clear();
Example:
localStorage.clear();
All stored data is removed.
Storing Numbers
Local Storage stores everything as strings.
Example:
localStorage.setItem("age", 20);
Actually stored as:
"20"
Storing Objects
Objects must be converted into JSON before storing.
Example:
let student =
{
name:"Rahul",
age:20
};
localStorage.setItem(
"student",
JSON.stringify(student)
);
Retrieving Objects
let data =
localStorage.getItem("student");
let student =
JSON.parse(data);
console.log(student.name);
Output:
Rahul
What is Session Storage?
Session Storage is similar to Local Storage.
The main difference is:
Data exists only during the current browser session.
When the browser tab is closed:
Data is automatically deleted.
Session Storage Characteristics
Temporary storage
Faster access
Tab-specific
Automatically cleared
Storing Data
sessionStorage.setItem(
"name",
"Rahul"
);
Retrieving Data
let name =
sessionStorage.getItem("name");
console.log(name);
Output:
Rahul
Removing Data
sessionStorage.removeItem("name");
Clearing Session Storage
sessionStorage.clear();
Session Storage Example
sessionStorage.setItem(
"loggedIn",
"true"
);
The user remains logged in while the tab is open.
Once the tab closes:
Session Ends
↓
Data Removed
Local Storage vs Session Storage
| Feature | Local Storage | Session Storage |
|---|---|---|
| Capacity | 5–10 MB | ~5 MB |
| Persistence | Permanent | Temporary |
| Browser Restart | Data Remains | Data Removed |
| Tab Closing | Data Remains | Data Removed |
| Use Case | User Preferences | Login Sessions |
What are Cookies?
Cookies are small pieces of data stored in the browser.
Unlike Local Storage:
Cookies are automatically sent to the server with every request.
Real-Life Example
When a user logs into a website:
Server
↓
Creates Cookie
↓
Browser Stores Cookie
↓
Future Requests Include Cookie
This helps the website recognize the user.
Cookie Structure
Name=Value
Example:
username=Rahul
Creating a Cookie
document.cookie =
"username=Rahul";
Reading Cookies
console.log(document.cookie);
Output:
username=Rahul
Creating Multiple Cookies
document.cookie =
"name=Rahul";
document.cookie =
"city=Kolkata";
Output:
name=Rahul; city=Kolkata
Setting Cookie Expiration
document.cookie =
"username=Rahul;
expires=Fri, 31 Dec 2027 12:00:00 UTC";
The cookie remains valid until the specified date.
Session Cookie
document.cookie =
"user=Rahul";
Without an expiration date, the cookie is deleted when the browser closes.
Deleting Cookies
document.cookie =
"username=;
expires=Thu, 01 Jan 1970 00:00:00 UTC";
The cookie is removed.
Cookie Attributes
| Attribute | Purpose |
|---|---|
| expires | Expiration date |
| max-age | Lifetime |
| path | URL path |
| secure | HTTPS only |
| SameSite | Security control |
Local Storage vs Cookies
| Feature | Local Storage | Cookies |
|---|---|---|
| Capacity | 5–10 MB | ~4 KB |
| Sent to Server | No | Yes |
| Speed | Faster | Slower |
| Storage Size | Large | Small |
| Security | Moderate | Better with HTTPOnly |
Practical Project – Dark Mode Preference
HTML:
<button onclick="enableDarkMode()">
Dark Mode
</button>
JavaScript:
function enableDarkMode()
{
document.body.style.background =
"black";
document.body.style.color =
"white";
localStorage.setItem(
"theme",
"dark"
);
}
Loading Saved Theme
window.onload =
function()
{
let theme =
localStorage.getItem(
"theme"
);
if(theme=="dark")
{
document.body.style.background =
"black";
document.body.style.color =
"white";
}
};
The theme remains active even after refreshing the page.
Practical Project – Visit Counter
let count =
localStorage.getItem("visits");
if(count==null)
{
count = 1;
}
else
{
count++;
}
localStorage.setItem(
"visits",
count
);
console.log(
"Visits: " + count
);
Output:
Visits: 1
Visits: 2
Visits: 3
Best Practices
Use Local Storage for user preferences.
Use Session Storage for temporary session data.
Use Cookies for authentication tracking.
Convert objects using JSON.stringify().
Retrieve objects using JSON.parse().
Never store passwords or sensitive information in Local Storage.
Real-World Applications
Browser storage is used in:
Dark Mode Settings
Shopping Carts
User Preferences
Remember Me Login
Language Selection
Analytics Tracking
Session Management
Modern websites rely heavily on browser storage to provide a smooth user experience.
Conclusion
Local Storage, Session Storage, and Cookies are essential tools for modern web development. They allow websites to remember information, improve performance, and provide a personalized experience.
Understanding when to use each storage mechanism is an important skill for every JavaScript developer.
Local Storage is ideal for permanent data, Session Storage is suitable for temporary sessions, and Cookies are useful when data needs to be shared with the server.
Comments
Post a Comment