Session Storage in JavaScript
Session Storage in JavaScript is a versatile client-side storage mechanism that allows developers to store data temporarily for a single session. It’s particularly useful for scenarios where data doesn’t need to persist beyond a browser session, such as maintaining form inputs or user preferences during navigation. Unlike Local Storage, session storage ensures that data is automatically cleared once the browser is closed. This makes it a lightweight, secure option for managing temporary data in web applications.
In this section, we’ll cover the following topics:
- What is Session Storage in JavaScript?
- How to Use Session Storage
- Implementing Session Storage with AI Assistance
What is Session Storage?
Session Storage is part of the Web Storage API and provides a way to store key-value pairs in a browser. Data stored in session storage is isolated to the specific tab or window and is cleared as soon as the session ends. It is ideal for use cases where temporary data is needed, such as tracking user interactions within a single session.
Why Choose Session Storage Over Local Storage?
While Local Storage persists data even after a browser is closed, session storage is designed for temporary use. Session Storage is preferred when:
- Data lifespan needs to match a session: For example, a user filling out a multi-step form.
- Security concerns exist: Sensitive data is automatically cleared at the end of a session.
- Resource efficiency: Session Storage reduces the risk of cluttering storage with unnecessary data.
How to Use Session Storage
Session Storage is straightforward to use and requires no additional libraries or tools. It offers simple methods to store, retrieve, and remove data. Below, we’ll explore these techniques.
Accessing the Session Storage Object
Session Storage can be accessed through the sessionStorage
object, which is globally available in JavaScript. For example:
console.log(sessionStorage);
This will output the current session storage content in the browser console.
Adding, Retrieving, and Deleting Data
To work with session storage, use the following methods:
- Adding data: Use
sessionStorage.setItem(key, value)
to add data. - Retrieving data: Use
sessionStorage.getItem(key)
to fetch stored data. - Removing data: Use
sessionStorage.removeItem(key)
orsessionStorage.clear()
to remove items.
Example:
// Adding data
sessionStorage.setItem("username", "JohnDoe");
// Retrieving data
let user = sessionStorage.getItem("username");
console.log(user); // Output: JohnDoe
// Removing data
sessionStorage.removeItem("username");
sessionStorage.clear(); // Clears all items
Implementing Session Storage with AI Assistance
Session Storage is a powerful tool, and leveraging AI can make implementation even more efficient. This section includes practical examples to help you get started.
Preparing for Practice Files
This course takes a hands-on approach, allowing you to apply the techniques covered in real-world scenarios. We'll be using a structured folder layout. Before proceeding with the examples, please ensure the following files are prepared:
/your-project-folder/
|─10-02-session-storage/ (<- sub-folder)
|─ example-1.css
|─ example-1.html
|─ example-1.js
For your convenience, these files are also available on our GitHub repository.
AI Case: Managing Form Data Across Page Reloads
In this case study, we’ll explore how session storage can retain form data during navigation or accidental page reloads. This functionality enhances user experience by preventing data loss.
Sample AI prompt:
Write JavaScript code to store form data in session storage and retrieve it when the page reloads.
Sample code output:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Session Storage Form</title>
<link rel="stylesheet" href="example-1.css" />
</head>
<body>
<div class="container">
<h1>Session Storage Demo</h1>
<p>
Fill out the form below. Your inputs will be saved temporarily and
restored if the page is refreshed.
</p>
<form id="userForm">
<label for="name">Name:</label>
<input
type="text"
id="name"
name="name"
placeholder="Enter your name"
/>
<label for="email">Email:</label>
<input
type="email"
id="email"
name="email"
placeholder="Enter your email"
/>
<button type="submit">Submit</button>
</form>
</div>
<script src="example-1.js"></script>
</body>
</html>
/* General styles */
body {
font-family: "Arial", sans-serif;
background-color: #f4f4f9;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
background: #ffffff;
padding: 20px 30px;
border-radius: 8px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
text-align: center;
width: 100%;
max-width: 400px;
}
h1 {
font-size: 1.8em;
color: #333;
margin-bottom: 15px;
}
p {
font-size: 0.9em;
color: #666;
margin-bottom: 20px;
}
form {
display: flex;
flex-direction: column;
gap: 15px;
}
label {
text-align: left;
font-size: 0.9em;
color: #444;
}
input {
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 1em;
}
button {
padding: 10px 20px;
border: none;
background-color: #4caf50;
color: #fff;
border-radius: 5px;
font-size: 1em;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
document.addEventListener("DOMContentLoaded", () => {
const form = document.getElementById("userForm");
const nameInput = document.getElementById("name");
const emailInput = document.getElementById("email");
// Load saved data
nameInput.value = sessionStorage.getItem("name") || "";
emailInput.value = sessionStorage.getItem("email") || "";
// Save data on input change
nameInput.addEventListener("input", () => {
sessionStorage.setItem("name", nameInput.value);
});
emailInput.addEventListener("input", () => {
sessionStorage.setItem("email", emailInput.value);
});
form.addEventListener("submit", (event) => {
event.preventDefault(); // Prevent form submission for this example
alert("Form data saved in session storage!");
});
});
Instructions to see the results:
Save the code above in their respective files. Open the HTML file in your browser.
Interact with the form, and refresh the page to see how session storage retains the form data.
Key Difference:
Session storage clears data when the browser is closed and is tied to the specific tab or window. If you copy the URL and paste it into a new tab, the filled data will not be loaded because session storage is unique to the original tab. In contrast, local storage applies saved user preferences across all tabs, so any preferences stored in local storage will be applied to the new tab.
Watch this video to see it in action:
To explore how Session Storage works, you can also visit the following link:
Reference links:
FAQ: Session Storage in JavaScript
What is Session Storage in JavaScript?
Session Storage in JavaScript is a versatile client-side storage mechanism that allows developers to store data temporarily for a single session. It’s particularly useful for scenarios where data doesn’t need to persist beyond a browser session, such as maintaining form inputs or user preferences during navigation. Unlike Local Storage, session storage ensures that data is automatically cleared once the browser is closed.
Why Choose Session Storage Over Local Storage?
Session Storage is preferred over Local Storage when the data lifespan needs to match a session, such as a user filling out a multi-step form. It is also beneficial for security concerns, as sensitive data is automatically cleared at the end of a session, and for resource efficiency, reducing the risk of cluttering storage with unnecessary data.
How to Use Session Storage?
Session Storage is straightforward to use and requires no additional libraries or tools. It offers simple methods to store, retrieve, and remove data. You can access the sessionStorage object globally in JavaScript to add, retrieve, and delete data using methods like sessionStorage.setItem(key, value), sessionStorage.getItem(key), and sessionStorage.removeItem(key).
What are the Key Differences Between Session Storage and Local Storage?
Session storage clears data when the browser is closed and is tied to the specific tab or window. If you copy the URL and paste it into a new tab, the filled data will not be loaded because session storage is unique to the original tab. In contrast, local storage applies saved user preferences across all tabs, so any preferences stored in local storage will be applied to the new tab.
How Can AI Assistance Enhance Session Storage Implementation?
Leveraging AI can make the implementation of session storage more efficient. For example, AI can help manage form data across page reloads, enhancing user experience by preventing data loss. Practical examples and case studies can guide developers in using AI to optimize session storage usage.