Ultimate Guide to Local and Session Storage

4 min readZeeshan Ali
Ultimate Guide to Local and Session Storage

What Are Local and Session Storage? Local Storage and Session Storage are tools that let you save small pieces of information in your browser. They’re like a notebook for your website! Unlike cookies, they can hold more data (up to 5-10 MB), are simple to use, and don’t send data to the server every time.

Key Differences:

  • Local Storage: Keeps data until you delete it, even if you close the browser. Great for things like your favorite settings.
  • Session Storage: Holds data only while your tab is open. It disappears when you close the tab. Perfect for temporary notes.

Step-by-Step: Saving a Name Let’s try saving and showing a name using both storages. Follow these easy steps:

  1. Make an HTML File: Create a new file and save it as index.html. Copy this code into it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Storage Fun</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>Try Local & Session Storage</h1> <input id="nameInput" type="text" placeholder="Type your name here"> <button onclick="saveName()">Save Name</button> <p>Your Name in Local Storage: <span id="localName"></span></p> <p>Your Name in Session Storage: <span id="sessionName"></span></p> <script src="script.js"></script> </body> </html>
  1. Make a CSS File: Create a file called styles.css and add this code to make it look nice:
1 2 3 4 5 6 7 8 9 10 11 12 body { font-family: Arial, sans-serif; text-align: center; padding: 20px; } input, button { margin: 10px; padding: 8px; } button { cursor: pointer; }
  1. Make a JavaScript File: Create a file named script.js and paste this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 function saveName() { const name = document.getElementById('nameInput').value; localStorage.setItem('userName', name); sessionStorage.setItem('userName', name); displayNames(); } function displayNames() { document.getElementById('localName').textContent = localStorage.getItem('userName') || 'None'; document.getElementById('sessionName').textContent = sessionStorage.getItem('userName') || 'None'; } displayNames();
  1. Test It Out:
  • Open index.html in your browser.
  • Type a name and click 'Save Name'.
  • Check if the name shows up for both storages.
  • Close the tab, then open it again: The Local Storage name stays, but the Session Storage name goes away.
Saving Names with Storage Demo
Figure 1: Seeing your name saved in Local and Session Storage.

Simple Sign-In Example Let’s create a basic sign-in system. It will save a user ID in Local or Session Storage and remove it when you sign out.

  1. Update HTML File: Replace the content of index.html with this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Sign-In Fun</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>Sign-In Demo</h1> <div id="loginForm" style="display: block;"> <input id="userId" type="text" placeholder="Type your User ID"> <button onclick="signIn('local')">Sign In (Local)</button> <button onclick="signIn('session')">Sign In (Session)</button> </div> <div id="userInfo" style="display: none;"> <p>Your User ID: <span id="currentUser"></span></p> <p>Storage Used: <span id="storageType"></span></p> <button onclick="signOut()">Sign Out</button> </div> <script src="script.js"></script> </body> </html>
  1. Update CSS File: Add this to styles.css to style it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 body { font-family: Arial, sans-serif; text-align: center; padding: 20px; } input, button { margin: 10px; padding: 8px; } button { cursor: pointer; background-color: #007bff; color: white; border: none; border-radius: 4px; } button:hover { background-color: #0056b3; } #userInfo { margin-top: 20px; }
  1. Update JavaScript File: Replace script.js with this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 function signIn(storageType) { const userId = document.getElementById('userId').value; if (!userId) { alert('Please type a User ID'); return; } const storage = storageType === 'local' ? localStorage : sessionStorage; storage.setItem('userId', userId); storage.setItem('storageType', storageType); updateUI(); } function signOut() { const storageType = localStorage.getItem('storageType') || sessionStorage.getItem('storageType'); const storage = storageType === 'local' ? localStorage : sessionStorage; storage.removeItem('userId'); storage.removeItem('storageType'); updateUI(); } function updateUI() { const userId = localStorage.getItem('userId') || sessionStorage.getItem('userId'); const storageType = localStorage.getItem('storageType') || sessionStorage.getItem('storageType'); if (userId) { document.getElementById('loginForm').style.display = 'none'; document.getElementById('userInfo').style.display = 'block'; document.getElementById('currentUser').textContent = userId; document.getElementById('storageType').textContent = storageType; } else { document.getElementById('loginForm').style.display = 'block'; document.getElementById('userInfo').style.display = 'none'; } } updateUI();
  1. Test It Out:
  • Open index.html in your browser.
  • Type a User ID and click 'Sign In (Local)' or 'Sign In (Session)'.
  • See your User ID and the storage type on the screen, with a 'Sign Out' button.
  • Click 'Sign Out' to remove your User ID.
  • Close the tab for Session Storage to see the ID disappear. For Local Storage, it stays until you sign out.
Sign-In Demo with Storage
Figure 2: Signing in and out using Local and Session Storage.
Sign-In with Local Storage
Figure 3: Signing in using Local Storage.
Sign-In with Session Storage
Figure 4: Signing in using Session Storage.

Why Use These Storages? They help save data on your computer without needing the server. Use Local Storage for things that should last (like settings), and Session Storage for short-term stuff (like a form you’re filling out).

Common Uses:

  • Local Storage: Saving your theme choice or offline data.
  • Session Storage: Keeping form data while you work or temporary login info.

How to Use Storage Tools: Here are the basic commands:

  • setItem(key, value): Save a piece of data with a name.
  • getItem(key): Get data using its name.
  • removeItem(key): Delete a specific piece of data.
  • clear(): Remove everything stored.

Example: Saving Form Data Let’s save an email in a form so it stays after refreshing.

  1. Update HTML: Add this form to index.html:
1 2 3 4 5 6 <div> <h2>Save Your Form</h2> <input id="emailInput" type="email" placeholder="Type your email"> <button onclick="saveForm()">Save Form</button> <button onclick="clearForm()">Clear Form</button> </div>
  1. Update JavaScript: Add this to script.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 function saveForm() { const email = document.getElementById('emailInput').value; localStorage.setItem('email', email); alert('Form saved!'); } function clearForm() { localStorage.removeItem('email'); document.getElementById('emailInput').value = ''; alert('Form cleared!'); } // Load saved email when the page opens document.addEventListener('DOMContentLoaded', () => { const savedEmail = localStorage.getItem('email'); if (savedEmail) document.getElementById('emailInput').value = savedEmail; });
  1. Test It Out:
  • Type an email and click 'Save Form'.
  • Refresh the page; the email should still be there.
  • Click 'Clear Form' to remove it.
Saving Form Data
Figure 5: Keeping your email saved with Local Storage.

Checking Storage with Developer Tools

  1. Open Developer Tools:
  • Right-click anywhere on the page and choose 'Inspect'.
  • Go to the 'Application' tab, then click 'Local Storage' or 'Session Storage' to see your data.
Looking at Storage in Developer Tools
Figure 6: Checking your stored data in the browser.

Best Tips for Using Storage

  • Use text data; turn objects into strings with JSON.stringify() and back with JSON.parse().
  • Check if storage works with if (typeof Storage !== 'undefined').
  • Don’t save sensitive info like passwords since anyone can access it with code.
  • Watch for storage limits; use try-catch to handle errors.
  • Remove old data to save space.

Mistakes to Avoid

  • Don’t assume storage always works (like in private mode).
  • Don’t save big data; use IndexedDB instead.
  • Don’t save objects without converting them; they might break.
  • Be careful with Session Storage if you open multiple tabs, as each tab has its own storage.

Final Thoughts: Local and Session Storage are great for saving data on your computer. Use them to make your website better, like with the sign-in example. Test them in different browsers to make sure they work everywhere.

About the Author: Zeeshan Ali loves coding and knows a lot about frontend, backend, AI, and blockchain. Check out my projects and lessons on GitHub: Zeeshan Ali's GitHub Profile.

Zeeshan Ali's GitHub Page
Figure 7: Visit Zeeshan Ali’s GitHub for more coding help.

Was this article helpful?

Local StorageSession StorageWeb Storage APIbrowser storagesign-in exampleeasy storageJavaScript basics
Zeeshan Ali profile picture

About Zeeshan Ali

Software Engineer specializing in Web/Mobile Apps, AI, Data Science, and Blockchain. Follow me on GitHub and LinkedIn.

More from Zeeshan Ali

View all articles →