✏ How to save data on the Client: Local Storage, Session Storage, Cookies
As you start building more complex applications, you'll likely run into a situation where you want to store small chunks of data on the Client. An online store with a shopping cart can't work unless the items within that cart are stored somewhere, while the customer navigates through different pages. If your website offers a dark mode or multiple languages, your visitors would probably prefer if they don't have to make that choice again and again for each subpage.
The three ways to store data in the client browser are
local storage
session storage
cookies
Which one you choose for your application depends on the specific use case. This table sums up similarities and differences for all three methods:
image from codepen.io/beaucarnes/pen/KmeRMx
✏ Local Storage and Session Storage
Those two are part of the Web Storage API. Data is stored as key/value pairs, where the value has to be a string. For more complex data like an object, you first have to JSON.stringify
it before storing.
Local Storage and Session Storage can be accessed through the global window object. They are different entities, meaning that data that's stored in window.localStorage
is not available in window.sessionStorage
. The syntax to read/write is the same for both, though.
For the below examples, I'll assume we've written a simple clicker game in React, and we want the user to be able to save their current progress/score, so they can resume the game after closing and reopening the tab/browser window.
Storing data
To store a piece of data, use the setItem
method:
let score = 9000;
let bestMove = 123;
const data = { score, bestMove };
window.localStorage.setItem('clickerGame', JSON.stringify(data));
You could run this code in a clickEvent handler for a "save" button for example, or you can periodically check the player's progress and update the storage accordingly. Updating works the same as setting, the existing data will be overwritten by the new values.
Retrieving data
Similarly to the setter, localStorage
also has a getter:
const storage = JSON.parse(window.localStorage.getItem('clickerGame'));
In the game, this would either be triggered by a "resume" button, or you can put it in a useEffect
hook / componentDidMount
.
Deleting data
You can either delete specific parts of the stored data, or clear the whole storage object:
window.localStorage.removeItem('clickerGame');
window.localStorage.clear();
As you can see, the usage of local storage or session storage is really quite simple and intuitive.
✏ Inspecting local/session storage in dev tools
If you're interested in what data any website is storing in your browser, open the dev tools and move to the "Application" tab. In a panel on the left, you can see dropdowns for all storage objects (also cookies) and inspect the data. Results will probably vary, depending on the general shadiness of the page.
✏ Cookies
Cookies are much older than the Web Storage API, and fundamentally different in that they're sent with each HTTP request in the request header. There's two types of cookies:
Session Cookies
Those only live while the tab/window is open. A typical use case would be online banking - while the user is logged in and performs transactions, their identity is validated by a session cookie. As soon as they close the tab/page, the cookie is lost.
Persistent Cookies
As these are stored permanently (at least unless a user deletes their cookies), they allow to set an expiration date.
Setting and getting cookies
Getting and setting a cookie with JavaScript is dead simple:
document.cookie = 'myCookie=TEST';
console.log(document.cookie) // myCookie=TEST
Unlike the local storage object, you can't access individual cookies, you can only read them all at once.
Setting an expiration date
To set an expiration date, use the expire
attribute with a date string:
document.cookie = 'myExpireCookie=BYE; expires=Thu, 31 Oct 2021 07:28:00 GMT';
Deleting a cookie
To delete a cookie, you have to set it again with an expiration date that's already passed:
document.cookie = 'myExpireCookie=BYE; expires=Sun Feb 28 2021 10:00:00 GMT';
There's a lot more to say about cookies, so far I've never used them when I built a page because there really wasn't any need, but I'll explore user authentication and authorisation next, so I guess I'll come back to this topic to write a bit more. I'll also leave the link to MDN docs below.
✏ Resources
✏ Recap
I've learned
how to read/write to the browser's
localStorage
andsessionStorage
objectshow to get/set cookies with JavaScript
✏ Next:
user authentication
user authorisation
✏ Thanks for reading!
I do my best to thoroughly research the things I learn, but if you find any errors or have additions, please leave a comment below, or @ me on Twitter. If you liked this post, I invite you to subscribe to my newsletter. Until next time 👋
✏ Previous Posts
You can find an overview of all previous posts with tags and tag search here: