When talking about caching or storing data for a website, there are three methods available; cookies, localStorage, and sessionStorage. We will in this tutorial explain each of these methods and how to implement them using JavaScript.
Disclaimer: Using cookies nowadays is considered an old, legacy way of caching data for a website. Consider using localStorage or sessionStorage instead.
What are Cookies?
Cookies are small pieces of data stored in your web browser on your device.
Since the memory limitation on a cookie is 4Kb, the amount of data you can store in it is limited. Some common use cases for cookies are;
- Storing a customer’s shopping cart
- Storing user preferences for a website visitor
- Storing user behavior (which links you have clicked, how long you visited certain pages, and more…)
Create a Cookie in JavaScript
It is straightforward to create a cookie in JavaScript. You create a cookie with the following code:
document.cookie = "cachedUsername=bullishvince1337";
This line of code adds a cookie with the key cachedUsername
and the value bullishvince1337
.
You can add SameSite=None Secure
to the string if you want to be able to fetch this cookie from other websites than the current one. Our line of code then looks like this:
document.cookie = "cachedUsername=bullishvince1337; SameSite=None; Secure";
That’s all there is to creating a cookie. Next, we’ll look at retrieving the cookie we just stored!
Get a Cookie Value in JavaScript
Retrieving a cookie is not as straightforward as creating one, but it’s still fast and easy to do, which is what we’ll show you now. All cookies for our website are stored in the document.cookie
object. Let’s start by printing out the object:
console.log(document.cookie); //Output = cachedUsername=bullishvince1337
To make this example a bit more realistic, let’s add a couple more cookies:
document.cookie = "prop1=Hello World; SameSite=None; Secure";
document.cookie = "prop2=Goodbye; SameSite=None; Secure";
Now, let’s see what document.cookie
contains:
console.log(document.cookie); //Output = cachedUsername=bullishvince1337; prop1=Hello World; prop2=Goodbye
The content inside document.cookie
is a string, so we can split each cookie and retrieve the one we want using regular JavaScript operations. Let’s write a function that takes in a key and returns the cookie value for that specific key:
function getCookie(key) {
return document.cookie
.split("; ")
.find(x => x.startsWith(`${key}=`))
?.split("=")[1];
}
We can call this function, assign the response to a variable, and then print it to the console:
const cookieValue = getCookie("prop1");
console.log(cookieValue); //Output = Hello World
Pretty easy, right?
Deleting a Cookie in JavaScript
Sometimes, you may want to delete a cookie programmatically. This is easily accomplished by setting the expiration date on your cookie to a date in the past. Here’s a function I created in JavaScript that takes in a key and deletes the cookie with that key:
function deleteCookie(key) {
document.cookie = key + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
}
You can now easily delete a cookie, here’s an example of it:
function getCookie(key) {
return document.cookie
.split("; ")
.find(x => x.startsWith(`${key}=`))
?.split("=")[1];
}
function deleteCookie(key) {
document.cookie = key + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
}
document.cookie = "x=foo";
console.log(getCookie("x")); //Output = foo
deleteCookie(x);
console.log(getCookie("x")); //Output = ReferenceError: x is not defined
A last note before we move on to sessionStorage and localStorage; one of the benefits of using cookies over the other methods is that they can easily be set to expire at a certain time. This benefit makes them a good choice for storing temporary data which should only be available for a short period of time.
localStorage – Persisting Data Locally Across Your Browser
localStorage works pretty much the same as cookies, meaning both store data locally across your browser. The main difference between localStorage and cookies is the memory limitation, where localStorage allows storage of up to 5 Mb per object while cookies have a limitation of 4 Kb per cookie.
You interact with the localStorage through the localStorage
object which enables communication with the Storage
interface of the Web Storage API.
Note: localStorage separate objects stored over HTTP and HTTPS. This means you will not be able to access storage objects set on websites loaded over HTTPS if you’re visiting a page loaded over HTTP.
Save Data to localStorage
You save data to localStorage by calling the localStorage.setItem
function. This function takes in two parameters, a key and a value.
Here’s an example of saving data to localStorage:
localStorage.setItem("myName", "Vincent");
All keys and values are stored as strings in localStorage. This means that if you want to save a JavaScript object to the localStorage, you have to stringify it as a JSON string before saving it to the localStorage.
let myObject = {
"name": "Vincent",
"age": 29
}
//Make sure to stringify your object before saving it to localStorage
localStorage.setItem("myObject", JSON.stringify(myObject));
Get Data From localStorage
Continuing on our previous example of saving data to localStorage, let’s now read the data we just saved to localStorage.
To get data from localStorage, you need to call the getItem
function. Remember that our data is stored as a JSON string in localStorage, so we should parse it as JSON when reading it.
let newobject = JSON.parse(localStorage.getItem("myObject"));
We can now print it to the console to verify that it works:
console.log(newObject);
/*Output
{
age: 29,
name: "Vincent"
}
*/
Removing and Clearing Data from localStorage
When you save data to localStorage, the data is saved even if you close your session or browser. Therefore, if the data you’ve saved for your website isn’t needed anymore, a good practice is to remove that data.
To remove an item from the localStorage you call the removeItem
function, like this:
localStorage.removeItem("myObject"); //This will remove myObject from localStorage
Sometimes, you may also want to clear all data saved to localStorage from your website. This is done by calling the clear
function:
localStorage.clear();
Keep in mind that calling the clear
function only removes data added to localStorage from your website, meaning all other data in localStorage connected to other websites will not be removed.
sessionStorage – Handling Page Data
sessionStorage is very similar to localStorage, except for the fact that sessionStorage data is cleared once the page session ends. Other than their lifecycle differences, they pretty much work the same and they have the same functions.
Save Data to sessionStorage
To save data to sessionStorage, you call the setItem
function in the sessionStorage
interface:
sessionStorage.setItem("myProp", "foo");
Get Data From sessionStorage
You can get data from sessionStorage by calling the same function as we do with localStorage, getItem
.
Here’s how we can retrieve the data we stored in the previous example:
let data = sessionStorage.getItem("myProp"); //data will get the value "foo"
Removing and Clearing Data From sessionStorage
You remove or clear the data from sessionStorage in the same way as you do with localStorage.
To remove specific data from sessionStorage, you call the removeItem
function:
sessionStorage.removeItem("myProp"); //Remove myProp from sessionStorage
And, to clear the whole sessionStorage, you call the clear
function:
sessionStorage.clear(); //Remove all data from sessionStorage
Keep Data When Webpage Refreshes
A common use case for sessionStorage is to save data from fields when a webpage refreshes.
Let’s say your webpage contains a long form users need to fill in. It would be considered a bad user experience if all filled-in fields were cleared if the user, by mistake, refreshed the page.
We can solve this by continuously saving the data into sessionStorage and if the page refreshes, we load the data into the form fields:
// Get the form field element from the DOM
let formField = document.getElementById("myFormField");
// (this will only happen if the page is accidentally refreshed)
if (sessionStorage.getItem("formData")) {
// Restore the content of the form field
formField.value = sessionStorage.getItem("formData");
}
// Listen for changes in the form field
formField.addEventListener("change", () => {
// And save the data into sessionStorage
sessionStorage.setItem("formData", formField.value);
});
Conclusion
In conclusion, there are three ways of caching and storing data locally for your website; cookies, localStorage, and sessionStorage. This tutorial has briefly explained the characteristics of each method and shown examples of how to use each one of them.
Cookies are generally considered an old way of caching data. Nowadays, you should use either localStorage or sessionStorage, depending on your use case.
localStorage stores your data as long as you do not remove the data programmatically or manually clear your web browser’s browsing data.
SessionStorage stores your data and keeps it available as long as your current webpage session is active. This means that if you close the current tab or your browser, it will delete all data stored in sessionStorage for your website.
We hope you enjoyed reading this tutorial and that it helped you understand what methods you can use to cache and save data for your website.
Wanna learn more about web development? We have this article explaining the difference between ===
and ==
, you should check it out here!