learn2kode.in

JavaScript Session Storage

What Is Session Storage in JavaScript?

JavaScript Session Storage is part of the Web Storage API that allows web applications to store data in the browser for a single browsing session. The data is automatically cleared when the browser tab or window is closed.
If you are looking for a JavaScript session storage tutorial for beginners, this topic is essential for handling temporary client-side data without using a backend or cookies.
Why Use Session Storage?
Session Storage is useful when data should exist only while the user is active on a page or website.
Key Benefits
This makes session storage ideal for temporary data storage in JavaScript.
How Session Storage Works
Session Storage stores data as key–value pairs, and both keys and values must be strings.

Basic Session Storage Methods

Save Data (setItem)
sessionStorage.setItem("username", "John");
Get Data (getItem)
let user = sessionStorage.getItem("username");
console.log(user);
Remove Specific Item
sessionStorage.removeItem("username");
Clear All Data
Storing Objects in Session Storage
Session Storage supports only strings. To store objects, use JSON.
let cart = {
  product: "Laptop",
  quantity: 1
};

sessionStorage.setItem("cartData", JSON.stringify(cart));
Retrieving the Object
let cartData = JSON.parse(sessionStorage.getItem("cartData"));
console.log(cartData.product);
This is a common pattern in JavaScript session storage with JSON.
Practical Example: Multi-Step Form
// Step 1
sessionStorage.setItem("email", "user@example.com");

// Step 2
let email = sessionStorage.getItem("email");
console.log(email);
Perfect example of how to use session storage in JavaScript for temporary workflows.
Session Storage vs Local Storage
Feature Session Storage Local Storage
Data lifetime Until tab closed Permanent
Scope Single tab All tabs
Use case Temporary data Preferences
Storage size Smaller Larger

When to Use Session Storage

When NOT to Use Session Storage

Session Storage is not secure or encrypted, so avoid storing private data.

Common Mistakes with Session Storage