Browser Side Storages

Browser Side Storages

localStorage and sessionStorage:

  1. They are called Web storage objects
  2. They allow to save key/value pairs in the browser, maxSize 5MB,
  3. Both have the same set of methods,
localStorage.setItem(key, value) // – store key/value pair.
localStorage.getItem(key) // – get the value by key.
localStorage.removeItem(key) // – remove the key with its value.
localStorage.clear() // – delete everything.
localStorage.key(index) // – get the key on a given position.
localStorage.length // – the number of stored items.
sessionStorage.setItem(key, value) // – store key/value pair.
sessionStorage.getItem(key) // – get the value by key.
sessionStorage.removeItem(key) // – remove the key with its value.
sessionStorage.clear() // – delete everything.
sessionStorage.key(index) // – get the key on a given position.
sessionStorage.length // – the number of stored items.

Browser Side Storages

localStorage and sessionStorage:

  1. Data stored in localStorage remains after page refresh, closing the tab or even after closing the entire browser window
     
  2. Data stored in sessionStorage remains after page refresh, but is lost on closing the tab or on closing the browser window
     
  3. The localStorage is shared between all windows with the same origin, so if we set the data in one window, the change becomes visible in another one
    - We only have to be on the same origin (domain/port/protocol), the url path can be different,

Browser Side Storages

localStorage and sessionStorage:

  1. You can also treat localStorage very similar to an object:
  2. these can only store strings, so for objects you'd need JSON methods.
// set key
localStorage.test = 2;

// get key
alert( localStorage.test ); // 2

// remove key
delete localStorage.test;

// Only Strings can be added
localStorage.user = JSON.stringify({name: "John"});

// accessing objects
let user = JSON.parse( localStorage.user );
alert( user.name ); // John

Browser Side Storages

localStorage and sessionStorage:

  1. Looping through
// One way is to loop over them as over an array:

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

// Another way is to use for key in localStorage loop, 
// just as we do with regular objects.
// It iterates over keys, but also outputs 
// few built-in fields that we don’t need:

// bad try
for(let key in localStorage) {
  alert(key); // shows getItem, 
//   setItem and other built-in stuff
}

// …So we need either to filter fields 
// from the prototype with hasOwnProperty check:

for(let key in localStorage) {
  if (!localStorage.hasOwnProperty(key)) {
    continue; // skip keys like "setItem", "getItem" etc
  }
  alert(`${key}: ${localStorage.getItem(key)}`);
}

// Or just get the “own” keys with Object.keys 
// and then loop over them if needed:

let keys = Object.keys(localStorage);
for(let key of keys) {
  alert(`${key}: ${localStorage.getItem(key)}`);
}

Browser Side Storages

Cookies:

  • Cookies are small strings of data that are stored directly in the browser.
  • One of the most widespread use cases is authentication:
    - Cookies are usually set by a web server using the response Set-Cookie HTTP header.
    - Then, the browser automatically adds them to (almost) every request to the same domain using the Cookie HTTP header.

  • Steps overview:
    - Upon sign-in, the server uses the Set-Cookie HTTP header in the API response to set a cookie with a unique “session identifier”.
    - Next time the request is sent to the same domain (API call), the browser sends the cookie over the net using the Cookie HTTP header.
    - So the server knows who made the request.

Browser Side Storages

Cookies:

  • Reading cookies
    The value of document.cookie consists of name=value pairs, delimited by ;. Each one is a separate cookie.
  • Writing to document.cookie
  • One cookie can only store 4KB data
document.cookie // cookie1=value1; cookie2=value2;

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies

Browser Side Storages

Cookies:

Few special cookies:

domain
domain=site.com

  • A domain defines where the cookie is accessible.
  • In practice though, there are limitations. We can’t set any domain.
  • There’s no way to let a cookie be accessible from another 2nd-level domain, so other.com will never receive a cookie set at site.com.
  • It’s a safety restriction, to allow us to store sensitive data in cookies that should be available only on one site.
  • By default, a cookie is accessible only at the domain that sets it.
  • Please note, by default, a cookie is not shared with a subdomain, such as forum.site.com.

Browser Side Storages

Cookies:

Few special cookies:

path
path=/mypath

  • The URL path prefix must be absolute.
  • It makes the cookie accessible for pages under that path.
  • By default, it’s the current path.

Browser Side Storages

Cookies:

Few special cookies:

expires, max-age

  • By default, if a cookie doesn’t have one of these attributes, it disappears when the browser/tab is closed. Such cookies are called “session cookies”
  • To let cookies survive a browser close, we can set either the expires or max-age attribute. max-Age has precedence if both are set.
  • expires=Tue, 19 Jan 2038 03:14:07 GMT
  • The cookie expiration date defines the time when the browser will automatically delete it (according to the browser’s time zone).
  • If we set expires to a date in the past, the cookie is deleted.

Browser Side Storages

Cookies:

Few special cookies:

secure
secure

  • The cookie should be transferred only over HTTPS.
  • By default, if we set a cookie at http://site.com, then it also appears at https://site.com and vice versa.
  • That is, cookies are domain-based, they do not distinguish between the protocols.​

Browser Side Storages

Cookies:

Few special cookies:

httpOnly

  • This attribute has nothing to do with JavaScript, but we have to mention it for completeness.
  • The web server uses the Set-Cookie header to set a cookie. Also, it may set the httpOnly attribute.
  • This attribute forbids any JavaScript access to the cookie. We can’t see such a cookie or manipulate it using document.cookie.​

Browser Side Storages

Cookies:

Third-party cookies

  • A cookie is called “third-party” if it’s placed by a domain other than the page the user is visiting.
  • For instance:
  • A page at site.com loads a banner from another site: <img src="https://ads.com/banner.png">.​