dev knowledge hub

Search
Close this search box.

Differences Between Local Storage, Session Storage, and Cookies | Explained

Table of Contents

Have you ever wondered how websites remember your preferences or login information even after you close the browser? All of this is made achievable by technologies like cookies, session storage, and local storage. 
In this article, we’ll look into each of these web storage options and find their differences in simple terms.
Local Storage, Session Storage, and Cookies

What are Local Storage, Session Storage, and Cookies?

Local Storage, Session Storage, and Cookies are all ways for websites to store data locally on your browser. Think of them as tiny storage units within your browser where websites can keep track of information.

Local Storage

Local Storage is like a spacious storage unit where websites can store data that needs to be persistent even after you close the browser. It’s like storing your favorite items in a box that you can access anytime you visit the website.

Important Things to Know about Local Storage:

  • Space: You can usually store between 5MB to 10MB of data, which is quite a lot.
  • Staying Power: Your data sticks around even if the user closes the browser, which is handy.
  • Privacy: Only the user can see the data, which makes it safe.
  • Using the Data: You can use methods like setItem(), getItem(), removeItem(), and clear() to work with the data easily.

Session Storage 

On the other hand, is more like a temporary storage locker. It’s perfect for storing data that only needs to be available during your current browsing session. Once you close the browser, the data stored in session storage disappears, like items in a locker when you leave the gym.

Important Things to Know about Session Storage:
  • Short Memory: It only remembers things while you’re browsing, so it’s not for keeping stuff long-term.
  • One Session at a Time: It works separately for each tab or window you have open.
  • Private Stuff: Just like local storage, only you can see the data, which keeps it safe.
  • Easy to Use: You can use methods like setItem(), getItem(), removeItem(), and clear() to deal with the data easily.

Cookies 

Cookies are like little notes that websites leave on your browser. They contain small pieces of data, such as your login information or site preferences. Unlike storage options, cookies have an expiration date and can be set to expire after a certain period.

Important Things to Know about Cookies:
  • Not Much Space: They can only hold about 4 KB of data, so they’re good for small things.
  • Can Expire: They can be set to disappear after a while, which is handy.
  • Both Sides Can Use Them: Both the website and your computer can read and write cookies, so they’re good for sharing info.
  • Work Everywhere: They work on all web browsers, so you’ll find them everywhere online.
  • Been Around a While: Cookies have been used since the early days of the web, so they’re well-known and trusted.

How Do They Work?

Local Storage and Session Storage work similarly, but with one key difference: persistence. Data stored in Local Storage remains even after you close the browser, while data in Session Storage is cleared when the session ends.

Cookies, on the other hand, work by sending data back and forth between the client (your browser) and the server (the website). When you visit a website, the server sends a cookie to your browser, which stores it locally. The next time you visit the same website, your browser sends the cookie back to the server, allowing it to recognize you and customize your experience.

Lifetime of Data

One of the significant differences between these storage options is the lifetime of the data they store.

  • Local Storage: Data persists even after closing the browser.
  • Session Storage: Data is cleared when the browsing session ends.
  • Cookies: Data can persist for a specified period or until manually deleted.

Syntax Example

Storing Data in Browser Storage
// Setting data in local storage
localStorage.setItem('username', 'example_user');

// Setting data in session storage
sessionStorage.setItem('token', 'example_token');

// Setting a cookie
document.cookie = "user=example_user; expires=Wed, 19 Apr 2024 12:00:00 UTC; path=/";
Retrieving Data from Browser Storage
// Getting data from local storage
const username = localStorage.getItem('username');

// Getting data from session storage
const token = sessionStorage.getItem('token');

// Getting data from cookies
const cookies = document.cookie.split(';');
const userCookie = cookies.find(cookie => cookie.trim().startsWith('user='));
const user = userCookie ? userCookie.split('=')[1] : null;

Storage Capacity

Each storage option comes with its own capacity limitations.

  • Local Storage: Typically allows more storage space compared to cookies and session storage, often several megabytes per domain.
  • Session Storage: Generally has a smaller storage capacity compared to local storage, limited to the current browsing session.
  • Cookies: Have a size limit of around 4KB per cookie and a maximum number of cookies per domain.

Side-by-Side Comparison

FeatureLocal StorageSession StorageCookies
Lifetime of DataData persists even after closing the browserCleared when the browsing session endsCan persist for a specified period or until deleted
Storage CapacitySeveral megabytes per domainLimited to the current browsing sessionAround 4KB per cookie and maximum per domain
AccessibilityAccessible across all pages of a websiteOnly accessible within the same sessionCan be accessed across multiple pages
Security ConcernsRelatively secure, susceptible to XSS attacksMore secure since data is cleared after sessionProne to security risks like CSRF
Use CasesIdeal for storing user preferencesSuitable for storing temporary dataCommonly used for authentication tokens
CompatibilityWidely supported by modern browsersWidely supported by modern browsersWidely supported by modern browsers
Data TypeSupports all types of dataSupports all types of dataLimited to string data type for key-value pairs
Browser SupportSupported by most modern browsersSupported by most modern browsersSupported by most modern browsers
Cross-Origin RequestsShares data across originsShares data within the same originShares data within the same origin
Data RetentionRetained until manually cleared or overwrittenCleared at the end of the sessionRetained until expired or manually deleted
APIProvides a straightforward API for data manipulationProvides a straightforward API for data manipulationProvides limited API for reading and writing cookies
Privacy ConcernsMay raise privacy concerns if misusedMay raise privacy concerns if misusedMay raise privacy concerns if misused
SpeedGenerally faster than cookiesGenerally faster than cookiesGenerally faster than local and session storage
Indexed by Search EnginesNot indexed by search enginesNot indexed by search enginesNot indexed by search engines
Usage in Web DevelopmentWidely used for various purposesWidely used for temporary data storageWidely used for user tracking and customization
Data PersistencePersistent across browser sessionsTemporary and cleared after the session endsPersistent or temporary based on expiration
ScalabilityScales well for large amounts of dataLimited scalability for large amounts of dataLimited scalability due to size constraints
Ease of UseRelatively easy to use and implementRelatively easy to use and implementRelatively easy to use and implement
Dependency on NetworkNo dependency on networkNo dependency on networkMay depend on network for setting and retrieval

Conclusion

In conclusion, local storage, session storage, and cookies are essential tools for web developers to store data locally on the client side. Understanding the differences between these storage options is crucial for building secure, efficient, and user-friendly websites.

FAQ

Cookies can store information, but it’s not recommended to store sensitive data like passwords in cookies due to security risks.
The lifespan of a cookie varies depending on how it’s set by the website, ranging from a few minutes to several years.

Local storage and cookies have their own security considerations, but both can be secure if implemented correctly.

No, session storage data is only accessible within the same browsing session and cannot be shared across tabs or windows.
Local storage can store various types of data, but developers should be mindful of browser storage limits and user privacy concerns.

Leave a Comment

Differences Between Local Storage, Session Storage, and Cookies | Explained