Cookies vs localStorage vs sessionStorage
The four places a browser keeps a page's data, and where a login token belongs: localStorage and the table of strings behind it, why it needs JSON, sessionStorage for a single tab, IndexedDB for real objects and large data, cookies that travel to the server (document.cookie, Set-Cookie and HttpOnly), and how to choose between them.
In this lesson
- 0:00 Intro
- 1:05 Keys and values
- 1:46 What survives a reload
- 2:30 Strings only
- 3:15 JSON in and out
- 3:54 One store per origin
- 4:22 The visitor's copy
- 4:58 Session storage
- 5:34 IndexedDB
- 6:22 Opening a database
- 7:07 Cookies
- 7:43 Cookies from a script
- 8:19 Cookies from the server
- 8:59 Which one to use
- 9:55 In one line
- 10:20 Next time
Here’s a question web developers get asked sooner or later: where should a page keep a login token, the string that proves you’re signed in? The browser offers four places: localStorage, sessionStorage, IndexedDB, and a cookie. All four will hold it. But in three of them, any script running on the page can read it, including one you didn’t write, and nothing you do will stop that. Only one can be locked.
By the end of this lesson you’ll know the four places themselves and what each one can hold, how long each one keeps your data, and who gets to see it: other tabs, other scripts, the server. Then you’ll know how to choose between them, and where that login token goes. Three questions tell the four apart all the way through: what each can hold, how long it keeps it, and who sees it.
The page
Most of the examples run on the page from the last lessons: Kestrel’s page, kestrel.html, with a heading, a Launch button, a fuel gauge and its crew list. The crew is back in the file:
<!DOCTYPE html>
<html>
<head>
<title>Kestrel</title>
<link rel="stylesheet" href="kestrel.css">
</head>
<body>
<h1>Kestrel: on the pad</h1>
<button>Launch</button>
<progress id="fuel" value="80" max="100"></progress>
<ul>
<li>Ada</li>
<li>Lee</li>
<li>Omar</li>
</ul>
<script src="mission.js"></script>
</body>
</html>
The stylesheet beside it, kestrel.css, has one rule, .aboard { color: green; }. And the script, mission.js, lets you mark who’s aboard by pressing a name, and remembers it:
const list = document.querySelector("ul");
function restore() {
const saved = JSON.parse(localStorage.getItem("aboard")) ?? [];
for (const item of list.children) {
const aboard = saved.includes(item.textContent);
item.classList.toggle("aboard", aboard);
}
}
restore();
list.addEventListener("click", (event) => {
if (event.target.matches("li")) {
event.target.classList.toggle("aboard");
const marked = document.querySelectorAll(".aboard");
const names = [...marked].map((item) => item.textContent);
localStorage.setItem("aboard", JSON.stringify(names));
}
});
window.addEventListener("storage", restore);
Save the three files in one folder, and serve the folder from your own machine. In a terminal, in that folder, run python3 -m http.server, then open http://localhost:8000/kestrel.html. A server matters here more than usual, for a reason the lesson comes to.
Press Ada and Omar, and they turn green. Reload the page, and they’re still green. Two lines of that script did it: localStorage.setItem("aboard", JSON.stringify(names)) saves the names, and JSON.parse(localStorage.getItem("aboard")) reads them back when the page loads. The sections below take those two lines apart.
The examples go into the console of the browser’s developer tools, one line at a time unless they say to paste a block whole. The console shows the value of each line, with strings in single quotes. Before each one, clear what earlier ones saved with localStorage.clear(), unless the example says to keep it.
Keys and values
We start with the simplest of the four. localStorage is an object the browser gives every page, the same way it gives you document. It isn’t part of the JavaScript language: the browser provides it, as it provides document and fetch. Behind it sits a store, a table with two columns, keys and values.
setItem takes one of each and writes a row. getItem takes a key and gives back its value. A key with no row gives you null, not an error:
localStorage.setItem("aboard", "Ada");
localStorage.getItem("aboard"); // 'Ada'
localStorage.getItem("docked"); // null
Call setItem again with the same key, and the new value takes the old one’s place. There’s still one row:
localStorage.setItem("aboard", "Omar");
localStorage.getItem("aboard"); // 'Omar'
localStorage.length; // 1
removeItem deletes one row, and clear empties the table:
localStorage.removeItem("aboard");
localStorage.getItem("aboard"); // null
localStorage.clear();
localStorage.length; // 0
Four methods, and that’s nearly all of it. length counts the rows, and key(0) gives the first key’s name. You’ll also see code like localStorage.fuel = 80. It writes the same kind of row, but the methods say what they do, so this lesson uses them.
What survives a reload
A reload throws the page away: the tree of elements, every variable, each class a script added. Then the browser builds it all again from the file and runs the script from the top. That’s why a class added by a click is gone after a reload unless something puts it back.
The store isn’t part of the page. The browser keeps it on your disk, among its own files, so it outlives the reload. It outlives the tab, too. Close the tab, come back tomorrow, and the row is still there. Quit the browser or restart the computer, and it’s still there. A row has no expiry date. A browser can still clear a site’s data on its own, though: when the disk is nearly full, or, in Safari, after seven days of use without a visit to the site.
Look at what doesn’t happen, too. With the network panel of the developer tools open, press a name: no request leaves the page. The server never hears about any of it.
Strings only
There’s a catch, and it’s in the value column. A store holds strings, and only strings. Hand setItem anything else, and it’s turned into a string on the way in, with no warning.
Save the number 80, and you get back the string "80". Add 5 to it, and the plus sign joins them as text:
localStorage.setItem("fuel", 80);
localStorage.getItem("fuel"); // '80'
localStorage.getItem("fuel") + 5; // '805'
For a number, converting it on the way out is enough: Number(localStorage.getItem("fuel")) + 5 is 85. A boolean comes back as a string too, which is the trap the next section but one is about:
localStorage.setItem("launched", false);
localStorage.getItem("launched"); // 'false'
An array fares worse. Its items come back as one string, joined by commas, with the brackets gone:
localStorage.setItem("aboard", ["Ada", "Omar"]);
localStorage.getItem("aboard"); // 'Ada,Omar'
An object fares worst. Whatever was in it, the store keeps fifteen characters:
localStorage.setItem("rocket", { name: "Kestrel", fuel: 80 });
localStorage.getItem("rocket"); // '[object Object]'
Keys go through the same treatment: setItem(1, 2) writes the key "1". null is saved as the four characters "null", and undefined as "undefined".
JSON in and out
So anything that isn’t a string has to become a string that keeps its shape. That’s JSON, the text format arrays and objects travel in. On the way in, JSON.stringify turns the array of names into text, brackets and quotes included, and that text is what the store keeps. On the way out, JSON.parse builds a real array from it again:
localStorage.setItem("aboard", JSON.stringify(["Ada", "Omar"]));
localStorage.getItem("aboard"); // '["Ada","Omar"]'
const saved = JSON.parse(localStorage.getItem("aboard"));
saved.includes("Ada"); // true
An object goes through the same way: JSON.stringify({ name: "Kestrel", fuel: 80 }) is '{"name":"Kestrel","fuel":80}', and parsing it gives back an object whose fuel is the number 80.
Those are the two lines from the start, and the script uses them in two places. On every press, the click listener finds the elements marked aboard, makes an array of their names, and saves it:
const marked = document.querySelectorAll(".aboard");
const names = [...marked].map((item) => item.textContent);
localStorage.setItem("aboard", JSON.stringify(names));
querySelectorAll gives a NodeList, so the three dots copy it into an array before map. When the page loads, restore reads the array back, and for each list item asks whether its name is in it. classList.toggle takes a second argument there: true adds the class and false removes it, so each item ends up marked or not, whatever it was before.
A false that counts as true
Save whether Kestrel has launched. It hasn’t, so save false. Then check it, and show liftoff if it’s set. Clear the store, reload the page, and paste this whole:
const heading = document.querySelector("h1");
localStorage.setItem("launched", false);
if (localStorage.getItem("launched")) {
heading.textContent = "Kestrel: liftoff";
}
The heading changes to Kestrel: liftoff, and the console shows no error from your code. (Chrome may log a 404 for favicon.ico, an icon for the tab, when the server has none. That line is about the icon.) You saved false, and the check treated it as true.
setItem turned false into a string, five characters long. And an if doesn’t read what a string says. It asks whether the value counts as true, and every string does, except the empty one. So the check passed, and the page showed liftoff.
The fix is the same habit as before: JSON.parse on the way out. It turns those five characters back into the real false, and on a first visit it turns null into null, which counts as false. Clear the store, reload the page, and paste this whole:
const heading = document.querySelector("h1");
localStorage.setItem("launched", JSON.stringify(false));
if (JSON.parse(localStorage.getItem("launched"))) {
heading.textContent = "Kestrel: liftoff";
}
The heading stays Kestrel: on the pad. JSON.stringify(false) is the same five characters setItem stored on its own, so the repair is in the read. Comparing with the text works too: localStorage.getItem("launched") === "true".
The first visit
The page works in your browser, because your store already has the key: you pressed names while you built the page. A visitor’s store has nothing. Take the default out of the read, so restore’s first line is just the parse:
const saved = JSON.parse(localStorage.getItem("aboard"));
Then open the page as a first-time visitor would. Clear the store from the console with localStorage.clear(), and reload. For a first visit, getItem gives null. JSON.parse takes null and hands back null with no complaint, because it reads the null as the text "null", which is valid JSON. Then the next line asks null whether it includes Ada, and that throws:
Uncaught TypeError: Cannot read properties of null (reading 'includes')
at restore (mission.js:6:26)
at mission.js:11:1
The script stops right there. The click listener below it is never added, so this visitor can’t save anything, ever: press a name and nothing happens.
The fix is a default, with the nullish coalescing operator, two question marks. It gives the right side whenever the left side is null or undefined:
const saved = JSON.parse(localStorage.getItem("aboard")) ?? [];
Put the default back, clear the store, and reload. A first visit now gets an empty array, the loop marks no one, the listener is added, and the first press saves. If a visitor edits the row by hand, the parse can still throw a SyntaxError; a try and catch round it covers that case too.
One store per origin
Which pages can read that row? Only the ones that share its origin: the scheme, the host and the port at the front of the address, here http://localhost:8000. Every page on that origin shares one store, in every tab, so two pages of one site can overwrite each other’s keys.
Another origin gets a store of its own, and it starts empty. Run a second server on another port with python3 -m http.server 8001, open http://localhost:8001/kestrel.html, and type:
localStorage.getItem("aboard"); // null
127.0.0.1 is the address localhost stands for, and http://127.0.0.1:8000/kestrel.html is the same machine and the same files. It’s a different origin, though, so its store is empty too. http and https are two origins as well.
A store also belongs to one browser. Open the page in a different browser, or on your phone, and nothing you saved has come along. And a page opened straight from your disk, with a file:// address, has a store whose rules depend on the browser. That’s the reason to use a local server here.
Two tabs
Open the page in two tabs. They share one store, but each has a tree of its own. Delete the last line of mission.js for a moment, reload both tabs, and mark Ada in the first: the second tab doesn’t change, because nothing has told it.
So the browser tells it. Whenever one tab changes the store, every other tab on that origin gets an event called storage. The event carries which key changed, its old value and its new one, and event.url says which page made the change. The tab that made the change doesn’t get it. Add a listener for it on window, the object that stands for the tab, and hand it the function that reads the store:
window.addEventListener("storage", restore);
Put that line back, reload both tabs, and a name pressed in one tab turns green in the other.
The visitor’s copy
The store lives on the visitor’s machine, so it’s theirs. In the developer tools, the Application panel lists it under Storage, then Local storage, then the origin. It shows the table, and the visitor can edit any row there or delete them all.
And any script running on your page can read every row: yours, a library’s, an ad’s. A script the page loads from another site runs with the page’s origin, so it reads the same rows. That rules localStorage out for the login token.
There’s a size limit, too: about five megabytes for each origin. Past it, setItem throws an error:
Uncaught QuotaExceededError: Failed to execute 'setItem' on 'Storage': Setting the value of 'x' exceeded the quota.
Reading and writing are synchronous, so a very large value holds the page up while it’s written. Keep in localStorage what’s small, not secret, and fine to lose.
Session storage
That’s the first of the four. The second is its twin, sessionStorage: the same four methods, strings only as well, the same rule about origins, and the same scripts can read it:
sessionStorage.setItem("draft", "Zoe");
sessionStorage.getItem("draft"); // 'Zoe'
What differs is how long a row lasts and who sees it. A sessionStorage row belongs to one tab. It survives a reload, but a second tab on the same page starts with an empty store of its own, and when the tab closes, its rows are gone for good. It’s kept for each origin too, so another site in the same tab can’t read it. So it suits whatever should last one visit and no longer, like a name typed into a form and not yet sent.
IndexedDB
The third is for what a table of strings can’t do. IndexedDB is a database, built into the browser, and what it keeps are real JavaScript values: numbers, booleans, arrays, dates, whole objects, even files. The object that localStorage turned into fifteen characters goes in as an object and comes out as an object, its fuel still a number and its launched still a boolean. No JSON going in, and none coming out. The one thing it refuses is a function: an object with a method in it makes put throw a DataCloneError.
There’s far more room, too: gigabytes on most machines, where localStorage stops at about five megabytes. How much depends on the browser and the disk: Chrome’s cap for one origin is 60% of the disk. And every call is asynchronous. You ask, your script carries on, and the answer arrives later, as an event, so even a large read doesn’t hold the page up.
It’s still one database for each origin, it lasts until it’s deleted, as a localStorage row does, and any script on the page can open it.
Opening a database
The price is the code. There’s no setItem here. Replace mission.js with this, reload the page, and look at the console:
const request = indexedDB.open("fleet", 1);
request.addEventListener("upgradeneeded", () => {
const db = request.result;
db.createObjectStore("rockets", { keyPath: "name" });
});
request.addEventListener("success", () => {
const db = request.result;
const transaction = db.transaction("rockets", "readwrite");
const rockets = transaction.objectStore("rockets");
rockets.put({ name: "Kestrel", fuel: 80, launched: false });
const read = rockets.get("Kestrel");
read.addEventListener("success", () => {
console.log(read.result); // {name: 'Kestrel', fuel: 80, launched: false}
});
});
You open a database by name, here fleet, and what comes back isn’t the database. It’s a request, and the script runs on to its last line before anything else happens. The answer arrives later, through the event loop, as an event called success, and request.result is the database from then on. Read it before that and you get an InvalidStateError.
On the first open, another event fires before it: upgradeneeded, the only place you can create an object store, IndexedDB’s name for a table. Each object here is kept under its name, the store’s keyPath. Reload the page and upgradeneeded doesn’t fire again, because the database already has that store. The 1 is the database’s version: raise it and upgradeneeded fires again, but then the listener must leave alone the stores that exist, because creating one twice throws a ConstraintError.
Then every read and write goes through a transaction, here one that may write, readwrite. put saves the object under its name (a second put with the same name replaces it), and get asks for it back, with one more request and one more success event for the answer. Ask for a key that isn’t there and the result is undefined, where localStorage gives null.
That’s nineteen lines for one row, where localStorage took two, so people often wrap the calls in a small library that hands back promises. Two such libraries are idb and Dexie. Here’s the same database with idb, loaded straight from a CDN as a module. Put it in a script tag with type="module", which is what lets await stand at the top level:
<script type="module">
import { openDB } from "https://cdn.jsdelivr.net/npm/idb@8/+esm";
const db = await openDB("fleet", 1, {
upgrade(db) {
db.createObjectStore("rockets", { keyPath: "name" });
},
});
await db.put("rockets", { name: "Kestrel", fuel: 80, launched: false });
console.log(await db.get("rockets", "Kestrel")); // {name: 'Kestrel', fuel: 80, launched: false}
</script>
Underneath, the library runs the same requests and events as the nineteen lines.
Cookies
The fourth is the oldest, and the odd one out: the cookie. Cookies date from 1994, about fifteen years before localStorage and IndexedDB. A cookie holds a small named string too, and a script can set one:
document.cookie = "aboard=Ada";
document.cookie; // 'aboard=Ada'
What sets a cookie apart is that it travels. The browser attaches a site’s cookies to every request it sends that site: the page, the stylesheet, each fetch. Reload Kestrel’s page, and the request for kestrel.css ends with this header:
GET /kestrel.css HTTP/1.1
Host: localhost:8000
…
Cookie: aboard=Ada
That’s their job. It’s how a server tells one visitor’s requests from another’s. Nothing in the other three travels: the server can’t see any of it unless your script sends it. And because a cookie rides on every request, it has to stay small: about four kilobytes at most. A browser drops a larger one without an error. Cookies also ignore the port, so localhost:8001 receives these ones as well.
Cookies from a script
document.cookie looks like a variable, and it doesn’t act like one. Assign it a name, an equals sign and a value, and you’ve added one cookie. Assign again with a different name, and the first is still there: now there are two. Read it, and you get every cookie in one string, with semicolons between them, and picking yours out is up to you. Clear the cookie from the last section first (the next paragraph shows how, or use the Application panel), then type these lines in turn:
document.cookie = "aboard=Ada";
document.cookie = "fuel=80";
document.cookie; // 'aboard=Ada; fuel=80'
The console also shows each assignment’s own string as its value; only the reads matter here. Assigning a name that’s already there replaces that one cookie.
To set how long a cookie lasts, add max-age, in seconds. Leave it off, and the cookie goes when the browser closes; some browsers bring such session cookies back when they restore your tabs. Set it to zero, and the cookie is deleted on the spot:
document.cookie = "fuel=80; max-age=86400";
document.cookie = "fuel=; max-age=0";
document.cookie; // 'aboard=Ada'
86400 seconds is one day. Quit the browser between those two lines and start it again, and fuel is still there while aboard, which had no max-age, is gone.
Cookies from the server
Usually, though, a cookie isn’t written by a script at all. The server sets it. Its response carries a header called Set-Cookie, and the browser stores the cookie before your JavaScript has done anything.
That’s how a login works. You send your password once, in a request like this one from a sign-in form:
POST /login HTTP/1.1
Host: localhost:8000
…
Cookie: aboard=Ada
name=ada&password=••••••••
The server answers with a cookie that holds your token:
HTTP/1.1 200 OK
Set-Cookie: login=k7m2x9; HttpOnly
And every request after that carries it back:
GET /sign-in.css HTTP/1.1
Host: localhost:8000
…
Cookie: aboard=Ada; login=k7m2x9
The server marked that cookie HttpOnly. Then no script on the page can read it: document.cookie doesn’t even list it, and assigning login= from a script doesn’t change it either.
document.cookie; // 'aboard=Ada'
So the login token goes there, in the one place of the four that can be locked. HttpOnly stops a script reading the token; a script on your page can still send requests that carry it. Two more attributes go with it on a real site: Secure, which sends the cookie over https only, and SameSite, which says whether the cookie goes along on a request that starts from another site’s page.
These three messages need a server that answers /login, which python3 -m http.server doesn’t. The next lesson writes one.
Which one to use
So that’s four places, and two questions sort them: who needs the data, and for how long?
- If the server needs it, it’s a cookie, and for a login, one the server sets with
HttpOnly. - If only this tab needs it, for this visit, it’s
sessionStorage. - If the page needs it next week, and it’s small, like a setting or a short list, it’s
localStorage, with JSON in and out. - And if there’s a lot of it, or it’s objects and files you want back as they were, it’s IndexedDB.
All four have one thing in common. They sit in the visitor’s browser, where the visitor can read them, change them and delete them: the Application panel lists all four under Storage, as Local storage, Session storage, IndexedDB and Cookies. All four are kept for each origin, except that cookies ignore the port, and a private window gets empty ones and forgets them when it closes. So anything your app can’t afford to lose, or to have changed, belongs on a server.
Summary
localStorageis a table of keys and values that the browser keeps on the visitor’s disk, outside the page, so it survives a reload, a closed tab and a restart.setItemwrites a row,getItemreads one (or givesnull),removeItemdeletes one, andclearempties the table.- It holds strings only:
80becomes"80", an array"Ada,Omar", an object"[object Object]", andfalsethe string"false", which counts as true. So useJSON.stringifyon the way in andJSON.parseon the way out, and give the read a default for a first visit:?? []. - There’s one store for each origin, in each browser, and any script on the page can read it. Other tabs on the origin hear about a change through the
storageevent. sessionStorageis the same table for a single tab, gone when the tab closes.- IndexedDB is a database for real values, and far more of them. Every call is a request whose answer comes back as an event; a small library can turn those into promises.
- Cookies are small strings that ride along on every request to the server. A script writes them through
document.cookie, and the server throughSet-Cookie; one markedHttpOnlycan’t be read by any script, which is why a login lives there.
Next in this series: JavaScript without a browser. Node runs JavaScript straight on your computer, with no page and no document, where a script can read files and answer requests as a server.
Video transcript
Intro
Here's a question web developers get asked sooner or later: where should a page keep a login token, the string that proves you're signed in? The browser offers four places: localStorage, sessionStorage, IndexedDB, and a cookie. All four will hold it. But in three of them, any script running on the page can read it, including one you didn't write, and nothing you do will stop that. Only one can be locked. So which one, and what are the other three for? Today, we find out.
By the end of this video, you'll understand three things. One: the four places themselves: localStorage, sessionStorage, IndexedDB and cookies, and what each one can hold. Two: how long each one keeps your data, and who gets to see it: other tabs, other scripts, the server. Three: how to choose between them, and where that login token goes.
Keys and values
We start with the simplest of the four. localStorage is an object the browser hands every page, the way it hands you document. Behind it sits a store: a table with two columns, keys and values. setItem takes one of each and writes a row. Here the key is aboard, and the value is Ada. getItem takes a key and gives back its value. Ask for a key that isn't there, and you get null, not an error. Call setItem again with the same key, and the new value replaces the old one. removeItem deletes one row, and clear empties the table. Four methods. That's nearly all of it.
What survives a reload
Now reload the page. The row is still there. Why? Because of where it's kept. A reload throws the page away: the tree of elements, every variable, each class a script added. Then the browser builds it all again from the file, and runs the script from the top. The store isn't part of the page. The browser keeps it on your disk, among its own files. So it outlives the reload. It outlives the tab, too. Close it, come back tomorrow, and the row is there. Quit the browser, restart the computer: still there. It has no expiry date. And look at what didn't happen. No request left the page. The server never heard about any of it.
Strings only
There's a catch, and it's in the value column. A store holds strings, and only strings. Hand setItem anything else, and it's turned into a string on the way in, with no warning. Save the number eighty, and what comes back is the string eighty. Add five to it, and the plus sign joins them as text: eight, zero, five. Save false, and it comes back as a string too, and an if counts any string but the empty one as true. An array fares worse. Save two names, and you get them back as one string, joined by a comma, with the brackets gone. An object fares worst. Whatever was in it, the store keeps fifteen characters: object Object, in square brackets.
JSON in and out
So anything that isn't a string has to become one that keeps its shape. That's JSON, the text format that arrays and objects travel in. On the way in, JSON dot stringify turns the array of names into text, brackets and quotes included, and that text is what the store keeps. On the way out, JSON dot parse builds a real array from it again. Two lines, and a page remembers a list through a reload. One thing is missing from them. On a first visit nothing has been saved yet, so getItem gives null, and the script needs a default: two question marks, then an empty array.
One store per origin
Which pages can read that row? Only the ones that share its origin: the scheme, the host and the port at the front of the address. Every page on that origin shares one store, in every tab. Another origin gets a store of its own, and it starts empty. Change the port, and the row isn't there. And a store belongs to one browser. Open the page in a different browser, or on your phone, and nothing you saved has come along.
The visitor's copy
One more thing about where the store lives. It's on the visitor's machine, so it's theirs. In the browser's developer tools, the Application panel shows the table, and they can edit any row there, or delete all of them. And any script running on your page can read every row: yours, a library's, an ad's. So that rules localStorage out for the login token. There's a size limit as well: about five megabytes for each origin. Past it, setItem throws an error. Keep what's small, not secret, and fine to lose.
Session storage
That's the first of the four. The second is its twin: sessionStorage. Same four methods, same strings, same rule about origins, and the same scripts can read it. What differs is how long a row lasts, and who sees it. A sessionStorage row belongs to one tab. It survives a reload. But a second tab on the same page starts with an empty store of its own. And when the tab closes, its rows are gone for good. So it suits whatever should last one visit and no longer, like a name typed into a form and not yet sent.
IndexedDB
The third is for what a table of strings can't do. IndexedDB is a database, built into the browser, and what it keeps are real JavaScript values: numbers, booleans, arrays, dates, whole objects, even files. The object that localStorage turned into fifteen characters goes in here as an object and comes out as an object. No JSON going in, and none coming out. There's far more room, too: gigabytes on most machines, where localStorage stops at about five megabytes. And every call is asynchronous. You ask, your script carries on, and the answer arrives later, so even a large read doesn't hold the page up. It's still one database for each origin, and any script on the page can open it.
Opening a database
The price is the code. There's no setItem here. You open a database by name, and what comes back isn't the database. It's a request, and the answer arrives later, as an event called success. On the first open, another event fires before it: upgradeneeded, the only place you can create an object store: IndexedDB's name for a table. Then every read and write goes through a transaction. put saves the object under its name, and get asks for it back, with one more event for the answer. That's a lot of steps for one row, so people often wrap them in a small library that hands back promises. Underneath, this is what runs.
Cookies
The fourth is the oldest, and the odd one out: the cookie. A cookie holds a small named string too. What sets it apart is that it travels. The browser attaches a site's cookies to every request it sends that site: the page, the stylesheet, each fetch. That's their job. It's how a server tells one visitor's requests from another's. Nothing in the other three travels. The server can't see any of it unless your script sends it. And because a cookie rides on every request, it has to stay small: about four kilobytes at most.
Cookies from a script
A script can write a cookie through document dot cookie. It looks like a variable, and it doesn't act like one. Assign it a name, an equals sign and a value, and you've added one cookie. Assign again with a different name, and the first is still there: now there are two. Read it, and you get every cookie in one string, with semicolons between them, and picking yours out is up to you. To set how long one lasts, add max-age, in seconds. Leave it off, and the cookie goes when the browser closes. Set it to zero, and the cookie is deleted on the spot.
Cookies from the server
Usually, though, a cookie isn't written by a script at all. The server sets it. Its response carries a header called Set-Cookie, and the browser stores the cookie before your JavaScript has done anything. That's how a login works. You send your password once. The server answers with a cookie that holds your token, and every request after that carries it back. And the server can mark that cookie HttpOnly. Then no script on the page can read it: document dot cookie doesn't even list it. Which brings us back to the question we started with. The login token goes here, in the one place of the four that can be locked.
Which one to use
So that's four places, and two questions sort them: who needs the data, and for how long? If the server needs it, it's a cookie, and for a login, one the server sets with HttpOnly. If only this tab needs it, for this visit, it's sessionStorage. If the page needs it next week, and it's small, like a setting or a short list, it's localStorage, with JSON in and out. And if there's a lot of it, or it's objects and files you want back as they were, it's IndexedDB. All four have one thing in common. They sit in the visitor's browser, where the visitor can read them, change them and delete them. So anything your app can't afford to lose, or to have changed, belongs on a server.
In one line
That's browser storage in one line: localStorage is a table of strings on the visitor's disk, one for each origin, with JSON on the way in and out; sessionStorage is the same table for a single tab; IndexedDB is a database for real values, and far more of them; and cookies are small strings that ride along on every request to the server, which is why a login lives there.
Next time
Next time, we leave the browser: Node, which runs JavaScript straight on your computer, with no page and no document, where a script can read files and answer requests as a server.

