JavaScript sessionStorage Explained: Store Data Per Session

6/29/2025
All Articles

JavaScript sessionStorage syntax example with setItem, getItem, removeItem, and clear

JavaScript sessionStorage Explained: Store Data Per Session

JavaScript sessionStorage Explained: Store Data Per Session

Introduction

Modern web applications often need to store data on the client-side to enhance performance and user experience. JavaScript provides the Web Storage API, which includes two powerful tools: localStorage and sessionStorage. This article focuses on sessionStorage, a key feature used to store data temporarily for a single session.

What is sessionStorage in JavaScript?

sessionStorage is a property of the Web Storage API that allows you to store key-value pairs in a web browser. Unlike localStorage, data stored using sessionStorage is only available during the page session. Once the browser tab is closed, the data is cleared automatically.

Key Features:

  • Stores data as key-value pairs.

  • Data persists only while the tab is open.

  • Accessible only from the same origin (protocol, host, and port).


Syntax of sessionStorage

// Set item
sessionStorage.setItem('username', 'JohnDoe');

// Get item
let user = sessionStorage.getItem('username');

// Remove item
sessionStorage.removeItem('username');

// Clear all items
sessionStorage.clear();

What is Session Storage?

Session Storage is also part of the Web Storage API. It works similarly to Local Storage but with one key difference: it only persists data for the duration of the browser session.

  • Temporary: Data is cleared when the page session ends.

  • Scope: Available only within the same tab or window.

  • Use Case: Ideal for storing session-specific state.

<!DOCTYPE html>
<html>
<head>
  <title>Session Storage Example</title>
</head>
<body>
  <input type="text" id="username" placeholder="Enter your name">
  <button onclick="saveName()">Save</button>
  <script>
    function saveName() {
      const name = document.getElementById('username').value;
      sessionStorage.setItem('username', name);
      alert("Name saved in session storage!");
    }

    // Retrieve and log value on page load
    window.onload = () => {
      const savedName = sessionStorage.getItem('username');
      if (savedName) {
        console.log("Welcome back, " + savedName);
      }
    };
  </script>
</body>
</html>

 

Conclusion

Local and Session Storage in JavaScript are handy ways to store data on the client side, either persistently or temporarily. They’re perfect for caching, state management, and enhancing user experience—just be cautious about security and storage limits.

Article