What is sessionStorage?
`sessionStorage` is a type of web storage that allows you to store key-value pairs in a web browser. The stored data remains intact only until the browser or tab is closed, making it an ideal choice for data that needs to persist across various pages of a single browser session.
Why use sessionStorage?
`sessionStorage` is useful when you need to persist data across different pages within a single browsing session. For instance, it can keep track of user activities during a single session or maintain the state of an application across page reloads. This information is erased once the session ends, offering an extra layer of security compared to other forms of storage such as `localStorage`, which retains data indefinitely unless it is explicitly removed.
Understanding the sessionStorage API
The `sessionStorage` object provides a simple API consisting of five main methods: `setItem()`, `getItem()`, `removeItem()`, `clear()`, and `key()`.
- sessionStorage.setItem(key, value)
The `setItem()` method allows you to add data to `sessionStorage`. It requires two arguments: a key that will identify the item, and a value, which is the data to be stored.
`getItem()` retrieves the value of the item identified by the supplied key. If the key does not exist, `getItem()` returns null.
`removeItem()` is used to remove an item from `sessionStorage`. It requires the key of the item to be removed as an argument.
The `clear()` method removes all items stored in `sessionStorage`. It does not require any arguments.
`key()` returns the name of the nth key in the storage. It takes an index as an argument and can be used to loop through all keys in `sessionStorage`.
Limitations of sessionStorage
While `sessionStorage` is a powerful tool, it has some limitations:
- Size Limit: Although the exact storage limit can vary between browsers, typically, `sessionStorage` can hold about 5-10MB of data.
- String-only storage: `sessionStorage` can only store strings. To store more complex data structures like objects or arrays, you need to serialize them using `JSON.stringify()` before storage and parse them using `JSON.parse()` after retrieval.
- Same-origin Policy: `sessionStorage` is subject to the same-origin policy, which means data stored will only be available from the same domain.
Example of storing and retrieving objects: