💾 Browser Storage

Introduction

Client-side storage in the browser is done using JavaScript APIs. We can use client-side storage to do many things, some examples include:

  • Saving site preferences for returning users. This could any number of things, but the most common use case is color scheme or dark/light theme preferences.
  • Persisted storage is commonly used to keep users logged in, and is probably one of the most valuable means of client-side storage for generating revenue. Noticed the items you put in your shopping cart before payday have been saved when returning to the site, or the items you viewed/searched for are now appearing across every social media you go on as adverts?
  • Saving data and assets to potentially increase page speed and performance for returning users.
FeatureCookiesSession StorageLocal Storage
Capacity~4 KB per cookie~5 MB~5 MB
PersistenceSet by expiry dateUntil tab closesUntil manually cleared
Sent to serverYes (every HTTP request)NoNo
Accessible fromServer + clientClient onlyClient only
ScopePer domain + pathPer tab + originPer origin
APIdocument.cookie (string)sessionStorage.*localStorage.*

*Note: we won't be covering Indexed DB or resource caching in this article.

Cookies

Definition

A cookie represents a small piece of information stored on a user's web browser after visiting a website.

Cookies have been around since the earliest days of the web to help store simple client-side data. Cookies are still used in modern-day web development for storing data such as sessions and access tokens. You don't need to use cookies though, we can use the newer web storage features via the Web Storage API. The Web Storage API claims to be easier and more intuitive to use for storing simple key values pairs.

When visiting a website using cookies, you should be prompted to accept or reject the various cookies with different intentions. Some cookies are needed for site functionality, others are just optional and may be used to capture data for marketing or analytical purposes. You can also delete cookies stored in your browser via JavaScript, browser dev tools, or just through the history settings UI.

Cookies have an individual maximum storage capacity of 4096 bytes. Each browser has a different max capacity for the number of cookies you can store. Chrome sits at 180 cookies, Firefox 150, and Android 50. Hopefully, you don't ever need to set anywhere near that capacity...

Cookies can be set by a responding server request using the Set-Cookie HTTP header, or via client-side JavaScript using the document.cookie property.

The document.cookie property acts as both a getter and setter.

Using Cookies

To set a cookie: document.cookie="the-joe-codes=123".

Getting by Name

To get a cookie by name, we could do something like:

1const getCookie = (name: string): string => document.cookie
2 .split('; ')
3 .find(cookie => cookie.startsWith(name))
4
5getCookie('the-joe-codes')
6
7// outputs: 'the-joe-codes=123'

Getting All

To see all available document cookies:

1document.cookie="the-joe-codes=123"
2document.cookie="another-cookie=đŸĒ"
3
4allCookies = document.cookie;
5
6// outputs: 'the-joe-codes=123; another-cookie=đŸĒ;'

This will print a string of all cookies, with each one separated by a semi-colon.

Setting Expirations

We can set the expiry date/time of a cookie:

1document.cookie="the-joe-codes=123; expires=Thu, 01 Jan 2023 00:00:00 UTC;"

Deleting Cookies

To delete a cookie using JavaScript we update the expiry date to some date/time in the past:

1document.cookie="the-joe-codes=; expires=Thu, 01 Jan 1970 00:00:00 UTC;"

Web Storage API

Definition

The Web Storage API can be used to store key/value pairs via sessionStorage and localStorage. The Web Storage API is newer and more intuitive than working with a list of delimiter separated cookies in a single string. Both session & local storage APIs sit on the Window object.

Session Storage

sessionStorage can hold data for the users' page session across each origin visited. Session storage is persisted across page reloads and browser tab restores. When the page session is killed (tab closed or browser closed), so is the session storage.

Session storage can hold up to 5MB of data, which is more than an individual cookie (4096 bytes).

Setting Session Storage

To set a session storage key value pair:

1sessionStorage.setItem('thejoecodes', '123');

Getting Session Storage

To get a session storage object by key:

1const sessionStorageItem = sessionStorage.getItem('thejoecodes');
2// 123

To see all session storage for a page:

1// set
2sessionStorage.setItem('thejoecodes', '123');
3
4// get all
5myStorage = window.sessionStorage;
6
7// logs object with Storage prototype:
8// {thejoecodes: '123', length: 1}

Deleting Session Storage

To delete a session storage object by key:

1sessionStorage.removeItem('thejoecodes');

To delete all session data stored for a page:

1sessionStorage.clear();

Local Storage

localStorage is similar to session storage. The key difference is persistence: local storage survives page reloads, tab restores, and the browser being closed and reopened. Like session storage, it is scoped to the same origin, so data stored on one domain is not accessible from another.

Local storage can hold up to 5MB of data, which is more than an individual cookie (4096 bytes).

Setting Local Storage

To set a local storage key value pair:

1localStorage.setItem('thejoecodes', '123');

Getting Local Storage

To get a local storage object by key:

1const localStorageItem = localStorage.getItem('thejoecodes');
2// 123

Getting All Local Storage

To see all local storage for a page:

1// set
2localStorage.setItem('thejoecodes', '123');
3
4// get all
5myStorage = window.localStorage;
6
7// logs object with Storage prototype:
8// {thejoecodes: '123', length: 1}

Deleting Local Storage

To delete a local storage object by key:

1localStorage.removeItem('thejoecodes');

Deleting All Local Storage

To delete all local data stored for a page:

1localStorage.clear();

Window Storage Event

This event fires when localStorage or sessionStorage has been modified.

1window.addEventListener('storage', () => {
2 console.log(JSON.parse(window.localStorage.getItem('thejoecodes')));
3});
4
5window.onstorage = () => {
6 console.log(JSON.parse(window.localStorage.getItem('thejoecodes')));
7};
Tip

The storage event only fires in other tabs or windows on the same origin, not the tab that made the change. This makes it useful for syncing state across tabs, for example keeping a user's login status consistent without polling.

Final Thoughts

If you want a fun exercise to see cookies, session storage and local storage in action, make sure to check out my interactive Christmas Challenge article!

Was this useful?

Thanks for reading! Time for one more?

const logger = () => console.log('yo!')
const theJoeCodes = () => logger()
theJoeCodes()
// call stack: theJoeCodes → logger → log

âš™ī¸ JS Runtime Env

20 Feb 2022 â€ĸ 📖 15 min read â€ĸ Updated 15 Mar 2026
🧙 Advanced topic

Understanding the JavaScript Runtime Environment with a focus on the Event Loop and Message Queues.

0
0
0
JAVASCRIPT
const xmas = christmasChallenge()
// 5 puzzles to unlock 🎅
xmas.santaSecretPassPhrase('???')
xmas.giveSantaFood('???')

🎅 Christmas Challenge

16 Dec 2021
👨‍đŸ’ģ Coding challenge

An interactive christmas challenge. Use your web dev skills to help Santa at the northpole 🎅.

0
0
0
JAVASCRIPT