session in javascript

In JavaScript, we can use session storage to store data for a user session across multiple pages. The data is stored on the client's browser and is available until the browser session is active.

To save data in session storage, we use sessionStorage.setItem() method. Here's an example of how to save a value in session storage:

index.tsx
// Save data to session storage
sessionStorage.setItem('key', 'value');
72 chars
3 lines

To retrieve data from session storage, we use sessionStorage.getItem() method:

index.tsx
// Get data from session storage
var value = sessionStorage.getItem('key');
console.log(value);  // Output: value
114 chars
4 lines

We can also remove data from session storage using sessionStorage.removeItem() method:

index.tsx
// Remove data from session storage
sessionStorage.removeItem('key');
70 chars
3 lines

Session storage is similar to cookies, but it is more secure as the data is stored on the client's browser and not sent to the server with each request. However, it is important to note that session storage is limited to the current browser tab and is lost when the tab is closed. Also, session storage is not supported by older browsers, so it is important to check if the browser supports it before using it.

Alternatively, we can also use local storage to store persistent data across browser sessions. Local storage works similar to session storage, but the data is not deleted when the browser is closed. To save data in local storage, we use localStorage.setItem() method instead.

gistlibby LogSnag