Key differences between Cookies and Local Storage

Both are used to remember your preferences or store information about your visit. That being said, what’s the difference between these two technologies, and when should you use each one?

What are Cookies?

Cookies were first introduced in the 1990s to store data such as login information or the content of your shopping cart. Each cookie is saved by your web browser as a name-value pair (e.g., ‘username=JohnDoe’) associated with a specific website — typically identified by the corresponding domain name. Whenever you visit that website again, the cookie is sent back to the server along with your request.

Here is a very simple snippet meant to set a cookie, then retrieve that information later on:

// Setting a new cookie (one by one).
document.cookie = 'username=JohnDoe; expires=Sun, 8 Dec 2023 12:00:00; path=/; domain=impakt.dev'
// Warning: If you try setting a new cookie with a past expiration date, or a domain not matching the document, it will be silently ignored!

// Retrieving all the document cookies.
const allCookies = document.cookie

N.B. The term “cookie” can refer to both the one-string representation of all the name-value pairs separated by semi-colons and each of those name-value pairs.

Cookies have limitations: their size is usually limited to 4KB, and they can only store simple data such as strings and numbers. They also have a limited lifespan, as they can be set to expire after a certain amount of time has passed.

What is Local Storage?

Local storage is a newer technology that was introduced with HTML5. Similarly to cookies, it allows websites to store data on the user’s computer.

While cookies are sent with every request to the server, local storage data is only stored on the user’s computer and is not sent to the server unless specifically requested by the website. One consequence is that local storage can be used to store larger amounts of data without affecting the performance of the website.

Local storage is more flexible than cookies, as it can store complex data types such as objects and arrays.

Unlike cookies, the local storage doesn’t set an expiration date. It gets cleared either via Javascript or by clearing the browser cache.

Here’s an example to set/get a value into/from the local storage:

// Setting a value in local storage.
localStorage.setItem('username', 'JohnDoe')

// Getting back the value from local storage.
const username = localStorage.getItem('username')

When should you use each of them?

Cookies and local storage serve different goals. A helpful rule of thumb is to think of the destination:

  • Cookies, sent with the HTTP header on each request, are meant to be read by the server.
  • Local storage, which can only be read by the client side, is meant to stay on the browser.