Unveiling the Intricacies of Local Storage and Session Storage (2024)

Unveiling the Intricacies of Local Storage and Session Storage (1)

January 17, 2024

In this blog we delve into the workings of Local and Session storage breaking down the nuances that set them apart

Introduction

In this post, we’re going to delve into the workings of Local and Session Storage. We aim to unravel not just their definitions, but more importantly, the nuances that set them apart. As developers, understanding these differences is crucial, akin to a carpenter knowing when to use a hammer versus a screwdriver.

For developers grappling with the choice between Local Storage and Session Storage, don’t worry, we’ve got you covered.

Unveiling the Intricacies of Local Storage and Session Storage (3)

What are Local storage & session storage?

Local Storage and Session Storage are two types of web storage that offer different ways of managing data in a web browser.

Local Storage is akin to etching data onto a stone tablet. Once stored, it persists across browser restarts and computer reboots, remaining until it’s explicitly removed by the user or through the clearing of the browser storage. Key uses include:

  • Token Storage for Authentication: Web applications store authentication tokens in Local Storage, allowing users to remain logged in across browser restarts.
  • Shopping Cart Data: E-commerce sites use Local Storage to keep shopping cart items even if the browser tab is closed.

An important aspect of Local Storage is its capacity limit, which is usually about 5MB. It’s also accessible only on the client side and is not secure for sensitive data. A more secure alternative for storing sensitive user data would be by using backend cookies, which prevents malicious XSS attacks notably due to their httpOnly flag. The httpOnly flag ensures that the cookie’s information is not readable by the client side JS, and instead only readable by the backend server that set them. You can learn more about cookies and how they compare to localstorage in our comparison blog.

Session Storage is more temporary, like a sandcastle. It holds data until that tab is kept alive. This means, that if the browser restarts, or if the tab is closed and new tab is opened, the sessionStorage for that page will be empty.. It’s useful for:

  • Form Data in Progress: Temporarily saving user inputs in forms across page refreshes or navigations (within the same browser tab).
  • Temporary User Preferences: Storing temporary settings or preferences during a single browser session, like filter settings on an e-commerce site.

Unlike Local Storage, Session Storage data is tab-specific. If you open the same site in two different tabs, they will each have their own separate Session Storage. This makes it ideal for situations where you don’t want data to persist across multiple tabs.

Both Local and Session Storage provide a simple and efficient way to store data on the client side without frequent server trips. However, due to their limitations in security and capacity, it’s crucial to use them judiciously and not for storing sensitive information.

FeatureLocal StorageSession Storage
PersistenceData persists across browser restartsData is cleared when the page session ends (typically when the browser tab is closed)
Capacity5 MB5 MB
Use casesToken Storage, Shopping CartsForm Data, Temporary User Preferences
ExpirationData does not expire; must be cleared manually or via scriptData expires automatically when the session ends.

Common Mistakes

Now, let’s talk about the digital Houdinis who bypass the persistence of Local and Session Storage. Sometimes, in an effort to be clever, developers or users might inadvertently make the application insecure or behave unexpectedly.

Common Mistakes for Local Storage

  • Not Managing Stored Data Over Time: Unlike Session Storage, Local Storage data remains until explicitly removed. A common error is not managing or cleaning up this data over time, leading to unnecessary bloat and potential performance issues.

  • Assuming Session-Like Behavior: Some developers mistakenly assume that data in Local Storage is tied to a session and will clear when the browser or tab closes. This misunderstanding can lead to privacy issues, as sensitive data such as passwords or credit card information might be left accessible on a shared or public computer.

  • Over-reliance on State Management: Using Local Storage extensively for managing application state can lead to complex synchronization issues, especially in dynamic applications where the state changes frequently. On the bright side, specialized frameworks such as Redux can be helpful in managing state in ReactJS based applications.

Common Mistakes for Session Storage

  • Expecting Cross-Tab Persistence: A key misunderstanding about Session Storage is expecting it to share data across tabs or windows. Data stored in Session Storage is only accessible in the window or tab where it was set, which can lead to confusion or data inconsistencies in applications opened in multiple tabs.

  • Using for Long-Term Storage: Since Session Storage is designed for data that only needs to persist during a single page session, using it for long-term data storage goes against its purpose. This can lead to data being lost unexpectedly when the browser or tab is closed.

Security Considerations

When diving into the world of web storage, it’s crucial to swim with caution, especially when it comes to security. Local Storage and Session Storage, while handy, open up a Pandora’s box of security vulnerabilities, notably cross-site scripting (XSS) risks.

Understanding XSS Dangers

An XSS attack occurs when a web application unwittingly includes untrusted data in a webpage, allowing attackers to inject malicious scripts into a web application. This is particularly concerning for Local and Session Storage, as they can become unwitting storage lockers for such harmful scripts. The following are three prominent real-life XSS attacks that occurred in the past two decades:

  • In 2010, YouTube faced a major XSS vulnerability where attackers injected malicious JavaScript into video comments, disrupting user experience and prompting security warnings. Source

  • In late 2015, eBay’s unvalidated URL parameter led to an XSS attack, enabling hackers to access seller accounts and steal payment details, with continued related attacks until 2017. Source

  • In 2018, Magecart hackers exploited an XSS flaw in British Airways’ website, redirecting customer data to a fake server, leading to credit card skimming in 380,000 transactions. Source

function validateInput(inputText) { // Regular expression to match only letters, numbers, and basic punctuation (.,!?) var pattern = /^[a-zA-Z0-9 .,!?]+$/; // Validate the input text return pattern.test(inputText);}

Think of it as a bouncer checking IDs at a club. Ensure that only the right data gets through.

Unveiling the Intricacies of Local Storage and Session Storage (4)

Next, employ Content Security Policy (CSP) which acts as a set of rules, dictating what’s allowed and what’s not in your webpage. The exact content that is allowed depends on the policies you define. One key feature of CSP is the ability to dictate which domains are allowed to serve JavaScript files. This control is crucial as it ensures that scripts are only loaded from trusted sources, significantly reducing the risk of malicious script injection. Similarly, CSP allows you to specify which domains can provide CSS files. By doing so, you ensure that only approved styles from trusted sources are applied to your site.

Conclusion

To sum up, effective use of Local and Session Storage is key in web development. Local Storage is best for long-term data, while Session Storage suits temporary, session-specific data. When dealing with local and session storage don’t forget to avoid common mistakes like mismanaging data and overlooking security risks, especially XSS attacks when building your app. Remember to include proper data handling, including both validation and encryption, as this is crucial for secure and efficient web applications. Mastering these tools ensures a better, safer user experience.

Unveiling the Intricacies of Local Storage and Session Storage (2024)

FAQs

What is the difference between session storage and local storage? ›

sessionStorage is similar to localStorage ; the difference is that while data in localStorage doesn't expire, data in sessionStorage is cleared when the page session ends. Whenever a document is loaded in a particular tab in the browser, a unique page session gets created and assigned to that particular tab.

Does local storage persist between sessions? ›

Since data stored in local storage persists across sessions and is accessible across all tabs and windows from the same origin, developers must be cautious about storing sensitive information, such as authentication tokens or personal data, in local storage.

What is the difference between storing token in local storage and session storage? ›

However, similar to local storage, session storage is susceptible to XSS attacks. Attackers can steal your tokens from the storage and use them to impersonate users. As such, it's also not advisable to store session tokens and other sensitive data in session storage.

What is the difference between angular localStorage and sessionStorage? ›

2)The main difference between Sessionstorage and localStorage is in sessionStorage the data is persisted only until the window or tab is closed, while with localStorage the data is persisted until the user manually clears the browser cache or until your web app clears the data by manually or by using clear data method.

Why is local storage better? ›

Because the data resides on a physical device, such as a computer or on-premises server, the user has more direct control over data privacy and security. Local storage also normally offers faster data access compared to cloud storage. Latency is reduced because data retrieval happens directly from a device.

What are 3 disadvantages of local storage? ›

Disadvantages of local storage
  • Higher costs: Upfront investment and ongoing maintenance of physical storage can be expensive.
  • Limited scalability: Enhancing storage capacity usually requires more hardware and physical space.
Apr 9, 2024

What is the limit of local storage and session storage? ›

Web Storage, which can be accessed by using the localStorage and sessionStorage properties of the window object, is limited to 10 MiB of data maximum on all browsers. Browsers can store up to 5 MiB of local storage, and 5 MiB of session storage per origin.

How long does data stay in local storage? ›

As we've seen, the data you store with localStorage doesn't expire; it stays indefinitely until you delete it manually. On the other hand, cookies can be set to expire after some time or as soon as you close the browser.

Why shouldn't you use localStorage? ›

Synchronous Blocking Operations: localStorage is not asynchronous and will block the main thread. It may even make your animations choppy depending on how much you read/ write and at what frequency. Asynchronicity is fundamental to creating fluid applications, especially for mobile devices.

Does local storage persist on refresh? ›

localStorage ) stores data that persists even when users close their browser tab (or window). In other words, whatever gets stored in the window. localStorage object will not disappear during a reload or reopening of the web page or when users close their browsers. Those data have no expiration time.

How long is sessionStorage accessible? ›

Session storage data will expire as soon as you close the tab you are on. This is because session storage is tied to a particular session which is equivalent to a tab so once you close your tab you are closing your session thus all session storage is cleared.

When to use session storage vs local storage? ›

Each of them has its unique characteristics and use cases.
  1. Local storage is useful for storing data that the user will need to access later, such as offline data, because it stores the data in the browser and the system. ...
  2. Session storage is a great way to improve the performance of your web applications.
Oct 4, 2023

What is the main difference between localStorage and sessionStorage lifetime scope? ›

2. What is Session Storage? Session Storage objects can be accessed using the sessionStorage read-only property. The difference between sessionStorage and localStorage is that localStorage data does not expire, whereas sessionStorage data is cleared when the page session ends.

Which methods are used for localStorage and sessionStorage? ›

Both storage objects provide the same methods and properties:
  • setItem(key, value) – store key/value pair.
  • getItem(key) – get the value by key.
  • removeItem(key) – remove the key with its value.
  • clear() – delete everything.
  • key(index) – get the key on a given position.
  • length – the number of stored items.
Oct 5, 2022

What is the difference between Express session storage and localStorage? ›

It does not interact with the server and is only changeable through JavaScript, with simple syntax. localStorage persists after a user exits the browser, while sessionStorage clears when the browser is exited. Per domain, localStorage can store 10mb while sessionStorage can store 5mb.

What is the difference between session storage and local storage MSAL? ›

Cache location options supported by MSAL are: local storage: MSAL uses browsers local storage to store its cache. session storage: MSAL uses the browsers session storage to store its cache.

What is sessionStorage used for? ›

Session storage allows you to store data in the browser depending on the system memory and the data stored in the browser until the browser is closed. In other words, closing the browser will clear all the data stored in session storage.

What is the difference between the two types of storage? ›

Every computer has both primary and secondary storage, with primary storage acting as a computer's short-term memory, and secondary as a computer's long-term memory.

Top Articles
How To Legally Take Down A Drone | Discovery Of Tech
Unlocking Crypto exchange in Malaysia: All in One Guide
Poe T4 Aisling
Victory Road Radical Red
Pitt Authorized User
Dr Lisa Jones Dvm Married
سریال رویای شیرین جوانی قسمت 338
Bill Devane Obituary
Edible Arrangements Keller
Oscar Nominated Brings Winning Profile to the Kentucky Turf Cup
RBT Exam: What to Expect
Nalley Tartar Sauce
Bnsf.com/Workforce Hub
Northeastern Nupath
NBA 2k23 MyTEAM guide: Every Trophy Case Agenda for all 30 teams
Vandymania Com Forums
Craigslist West Valley
St. Petersburg, FL - Bombay. Meet Malia a Pet for Adoption - AdoptaPet.com
Azpeople View Paycheck/W2
Invitation Homes plans to spend $1 billion buying houses in an already overheated market. Here's its presentation to investors setting out its playbook.
Understanding Genetics
Cvs El Salido
Great Clips Grandview Station Marion Reviews
Jc Green Obits
Low Tide In Twilight Ch 52
Lines Ac And Rs Can Best Be Described As
Mythical Escapee Of Crete
Pawn Shop Moline Il
Blackboard Login Pjc
Things to do in Pearl City: Honolulu, HI Travel Guide by 10Best
Planned re-opening of Interchange welcomed - but questions still remain
Trust/Family Bank Contingency Plan
Account Now Login In
Chadrad Swap Shop
Personalised Handmade 50th, 60th, 70th, 80th Birthday Card, Sister, Mum, Friend | eBay
Pawn Shop Open Now
Today's Gas Price At Buc-Ee's
Blasphemous Painting Puzzle
Pp503063
Temu Y2K
Restored Republic June 6 2023
Simnet Jwu
Www.craigslist.com Waco
The Attleboro Sun Chronicle Obituaries
3 Zodiac Signs Whose Wishes Come True After The Pisces Moon On September 16
'The Night Agent' Star Luciane Buchanan's Dating Life Is a Mystery
Iron Drop Cafe
Unpleasant Realities Nyt
The Missile Is Eepy Origin
Kindlerso
Latest Posts
Article information

Author: Ouida Strosin DO

Last Updated:

Views: 6402

Rating: 4.6 / 5 (76 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Ouida Strosin DO

Birthday: 1995-04-27

Address: Suite 927 930 Kilback Radial, Candidaville, TN 87795

Phone: +8561498978366

Job: Legacy Manufacturing Specialist

Hobby: Singing, Mountain biking, Water sports, Water sports, Taxidermy, Polo, Pet

Introduction: My name is Ouida Strosin DO, I am a precious, combative, spotless, modern, spotless, beautiful, precious person who loves writing and wants to share my knowledge and understanding with you.