Javascript - A Practical guide to use LocalStorage and SessionStorage
Tags: javascript
Published: 2020-05-24 13:15:59

## SessionStorage

`SessionStorage` is a simple key/value pair storage and only the string type of data can be stored. It is a tab specific storage and the data stored in `SessionStorage` will be lost when that tab is closed. We can store upto 5MB of data in this storage. Data stored in `SessionStorage` cannot be accessed from another tab. 

## LocalStorage

`LocalStorage` is also a simple key/value pair storage and only the string type of data can be stored. The data stored in `LocalStorage` is shared between all tabs for same domain. There is no expirations for the data in `LocalStorage` so it is always there even if you close the tabs or restart your system.


&nbsp;

## Check if the browser supports it

```jsx
if(typeof(Storage) !== void(0))
{
  // Your browser support localStorage and sessionStorage
}
else{
  // Sorry! No web storage support..
}
```

&nbsp;

## Storage API

`SessionStorage` and `LocalStorage` both has same API. Both storage objects provide same methods and properties. Following examples shows the API usage for localStorage and since they use same API, feel free to replace `localStorage` with `sessionStorage`


&nbsp;

### Store an Item

```jsx
// Store a simple string
localStorage.setItem('my-key', 'my-value');

// Store an object (Must be converted to string)
localStorage.setItem('my-object-key', JSON.stringify({key: 'value'}));
```


&nbsp;

### Get an Item from Storage

```jsx
localStorage.getItem('my-key'); // Returns string: 'my-value'

localStorage.getItem('my-object-key'); // Returns string: '{"key":"value"}'

JSON.parse(localStorage.getItem('my-object-key')); // Returns object: {key:"value"}
```

&nbsp;

### Remove an item

```jsx
localStorage.removeItem('my-key');
```


&nbsp;

### The number of stored items

```jsx
localStorage.length // Return count of items stored
```


&nbsp;

### Get the key on a given position

```jsx
localStorage.key(0); // Returns key of the item at very first position
```


&nbsp;

### Get all keys

```jsx
Object.keys(localStorage); // Returns array of all keys
```


&nbsp;

### Get all items

```jsx
for(let i = 0; i < localStorage.length; i++){
  const key = localStorage.key(i);
  const value = localStorage.getItem(key);
  console.log(key, value)
}
```


&nbsp;

### Remove everything from storage

```jsx
localStorage.clear(); // Removes everything from localStorage
```


&nbsp;

## Storage Event

When the data gets updated in `LocalStorage` or `SessionStorage`, the storage event is triggered with following properties:

- `key` - The name of key that was changed. (It will be `null` if `.clear` was called)
- `oldValue` - The old value of changed key. (It will be `null` if it is newly added)
- `newValue` - The new value of changed key.  (It will be `null` if the key was removed)
- `url` - The URL where the change happened
- `storageArea` - `localStorage` object or `sessionStorage` object depending on where it was updated.

> Storage event is triggered on all window objects of same domain excepts the one that triggered it.


&nbsp;


### Listen for events

```jsx
window.addEventListener('storage', function(e){
  console.log(e.key, e.oldValue, e.newValue, e.url, e.storageArea)
});
```

> Storage event triggered when the value is actually changed. Setting same value won't trigger the event.


&nbsp;

### Listen for a specific key change

```jsx
window.addEventListener('storage', function(e){
  if(e.key === 'my-key')
  {
    // Do your thing
  }
});
```


&nbsp;

## Things to remember

- `LocalStorage` and `SessionStorage` allow to store key/value (`String` only).
- Storage event triggers on `setItem`, `removeItem`, `clear` calls.
- The event triggers on all `window` objects where the storage is accessible, except the one that caused it.
- Refreshing the page doesn't remove data from `SessionStorage`
- Closing the browser or rebooting your system doesn't remove data from `LocalStorage`
- Do not store sensitive user information in `LocalStorage` or `SessionStorage`

&nbsp;

This was originally posted on my blog, check it out here: [https://nive.sh/practical-guide-to-use-localstorage-and-sessionstorage](https://nive.sh/practical-guide-to-use-localstorage-and-sessionstorage)