LoginSignup
2
0

More than 3 years have passed since last update.

Introduction to Cookies & Storage (Local and Session Storage)

Posted at

If you have been working on frontend development for quite some time, undoubtedly you will encounter cookies and storages at some point.

So, what are they?

Cookies

Cookies in terms of software development are information stored in a file or several files on your computer by websites that you visit.

A cookie...

  • Is a pretty old technology dating back to 1994.
  • Is used mainly for state management (it remembers your logins, shopping carts), personalization (user preferences), and tracking (might be used for recording and analyzing user behavior).
  • Is small-sized, up to 4096 bytes (~4kb).
  • Can be accessed server-side or client-side.
  • Has a lifetime depending on its definition. Session cookies are deleted when the user's browsing session ends, while permanent cookies last until its Expires date attribute or Max-age attribute.
  • Uses key-value pairings.

How to make secure cookies

Use Secure attribute

This ensures cookies to be sent only to the server on encrypted requests over HTTPS, never over HTTP. It's better to use this attribute in tandem with HttpOnly.

Use HttpOnly attribute

Despite its potentially confusing name (as it contradicts the above attribute!), this attribute prevents access of cookies using Document.cookie API by ensuring they are sent only to the server. This helps mitigating XSS (cross-site scripting) attacks.

Shorten the lifetime of sensitive cookies

If cookies are used to store user-related information such as authentication, it's better to set a short lifetime.

Combined all three together, we can set up a cookie like:

Set-Cookie: id=[value]; Expires=[date]; Max-Age=[age]; Secure; HttpOnly
Set-Cookie: id=cookie_id; Expires=Thu, 16 June 2020 06:30:00 GMT; Max-Age=2592000; Secure; HttpOnly

If both Expires and Max-Age exist, Max-Age has precedence.

Set SameSite attribute

Cookies misuse can lead to CSRF (cross-site request forgery). Let say you visited an e-commerce website (A). The website links to another website (B) that hosts some of the images for the product you are browsing. While sending request for images to B, cookies belong to that website might be sent along, thus potentially enabling B to know what are you doing in A.

We can, for instance, block all third-party websites` cookies to prevent CSRF, but that might lead to a poor browsing experience.

Instead, we should be setting SameSite attribute. By doing so, we can control whether to allow cookies to be sent along for requests initiated by third-party websites. For example:

Set-Cookie: SameSite=Lax; 
Set-Cookie: SameSite=Strict;

You can read a much complete explanation here.

Local storages

Local storages in terms of software development, as the name implies, are storages stored locally in your computer by websites that you visit. It might sound similar to cookies because, in a sense, they have a similar purpose! But here's the difference.

Local storage...

  • Came into prominence around the early 2010s.
  • Is usually used for personalization (user preferences, preferred theme) that is not sensitive data.
  • Has max size up to 10MB depending on the browser that you use (much bigger than cookie).
  • Has no expiration time.
  • Can only be accessed on the client-side via window.localStorage. This means on each HTTP request, data in local storage is not sent to the server.
  • Uses key-value pairings, always in UTF-16 format.

Note: Don't confuse local storage with cache storage. That's an entirely different storing method.

On security

Local storages store information as is, and it has no data protection. Period. So obviously we should never store in local storage sensitive data such as:

  • User & sessions IDs
  • JWTs (JSON Web Tokens)
  • Personal information
  • Any credit card related information
  • API keys

And since local storages are pure JavaScript, there's no telling that a malicious script may access your storages and pull out all the information there since it's quite easy to loop over storage without knowing the keys.

Something like:

for (let i = 0; i < localStorage.length; i++) {
  let key = localStorage.key(i);
  console.log(`${key}: ${localStorage.getItem(key)}`);
}

What about session storage?

It's basically just local storage with a limited lifetime. Session storages exist as long as the webpages/browser tabs that initiated them are alive.

  • If you open a site in several browser tabs, each browser tab will have different session storage.
  • If you do a page refresh, the data stays. But closing the tab will remove the data.

I personally have never used session storage. Feel free to let me know what would be the optimum usage.

Closing

This short article (more like a memo) is nothing spectacular. Other people might have written something more comprehensive regarding this topic.

So why did I do this?

Because I'm a firm believer that if you want to remember something, write it down in your own words and you will remember it better. And it's been working great for me so far! ^^

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0