JavaScript Session Storage

JavaScript Session Storage

How to Use Session Storage in Web Apps: An End-to-End Guide

ยท

5 min read

In the realm of web development, creating seamless user experiences is paramount. One powerful tool in a developer's arsenal for achieving this goal is session storage. In this article, we'll delve into session storage, understand its capabilities, and explore how it can elevate web interactivity to new heights.

This mirrors local storage but operates within the confines of a browser session. If you've already perused my Local Storage blog, you can bypass the entire description section, except for the segment on Data Persistence. In this section, I've delineated the disparities in data storage methods.

What is Session Storage?

The sessionStorage object stores data only for a session. It means that once the user closes the browser or tab or window, the session storage is cleared, making it ideal for storing temporary data or session-specific information.

Data Persistence

  • When you open a page in a new tab or window, the web browser creates a new session.

  • The browser clears the session storage when the browser session ends means the browser, tab, or window is closed.

  • The page session is valid only for the particular tab.

  • Session Storage survives over page reloads

  • Opening multiple tabs or windows with the same URLs creates a separate Session Storage for each tab.

  • Duplicating a tab copies the tab's Session Storage.

How Session Storage Works?

It works through Browser Apis.

MethodsDescription
setItem()To add data in LocalStorage.
getItem()To retrieve the data from LocalStorage
removeItem()To delete data from LocalStorage using a key
clear()To remove all the LocalStorage items
key()To retrieve data(key name) from LocalStorage at a specified index
length()To get the number of key/value pairs.
  • Data Structure - key: value (value is always string in Session Storage)

    • Local Storage can't store data other than strings. If in case you want to store an object or array then you have to stringify it first then you can store it.

setItem( )

This method is used to store data in sessionStorage. It accepts a key as its first argument and then a value as the second argument.

sessionStorage.setItem("name", "Subham Dash");

As I told Session Storage stores data as strings, so if you want to save data such as objects and arrays, you need to convert them to strings using the JSON.stringify() method.

//Storing objects in sessionStorage
const userDetails = {
  name: "Subahm Dash",
  location: "Bangalore",
  age: 26,
  hobby: "Writing blogs on web development"
};

sessionStorage.setItem("userDetails", JSON.stringify(userDetails));

//Storing arrays in LocalStorage
const closeFriends = ["Subham", "Rahul", "Chandan"];
sessionStorage.setItem("names", JSON.stringify(closeFriends));

getItem()

  • Use the getItem() method to retrieve data from sessionStorage. This method accepts a single parameter, which is key used when saving data.

  • For data that are objects or arrays, we can parse them after getting the values.

sessionStorage.getItem("name");
// output : 'Subham Dash'

sessionStorage.getItem("userDetails");
// output : '{"name":"Subahm Dash","location":"Bangalore","age":26,"hobby":"Writing blogs on web development"}'

JSON.parse(sessionStorage.getItem("closeFriends"))
// output: ["Subham", "Rahul", "Chandan"]

removeItem()

Use the removeItem() method to remove data from LocalStorage. This method accepts an key as a parameter.

sessionStorage.removeItem("name");
sessionStorage.removeItem("userDetails");

here, from the sessionStorage name and userDetails, key-value pairs get deleted.

clear()

Use the clear() method to remove all the data from sessionStorage.

sessionStorage.clear();

key()

Use key(index) method to retrieve data(key name) from sessionStorage, where index represents the nth data you want to retrieve.

sessionStorage.key(3);

length()

Use the length() method to get the number of keys present in the sessionStorage at the current moment.

sessionStorage.length()

Size Limit

  • The limit for most browsers is around 5 to 10 megabytes per origin.

Synchronous or Asynchronous

  • It is synchronous, which means it will block your main thread and do your computation until and unless it is done, it won't move ahead

How to Access Session Storage in Browser

  • Go to any website or web application and open the browser console by pressing F12 on the keyboard.

Next, click on the Application tab, and in the menu on the left, you will see Session Storage in the Storage tab as shown below.

Practical Applications of Session Storage

Temporary User Preferences:

Session storage can be used to store temporary user preferences or settings during a browsing session. This allows for personalized experiences without the need for long-term storage.

Form Data Persistence:

Web forms often require users to fill in multiple fields across different pages. Session storage can be leveraged to retain form data temporarily, ensuring a seamless user experience even when navigating between pages.

Session-Specific State Management:

Session storage is ideal for managing session-specific states within web applications. This includes maintaining the state of a multi-step process, preserving user progress, or managing a temporary application state.

Conclusion:

Session storage emerges as a valuable asset for web developers seeking to enhance web interactivity and user experiences. By leveraging the capabilities of session storage, developers can ensure data persistence, improve security, and streamline session-specific interactions. Let's embrace the potential of session storage and elevate the web experiences we create. Happy coding!

Feel free to share your thoughts and experiences with session storage in the comments below! Let's continue exploring the endless possibilities of web development together.

ย