Cookies

  • Cookies are small strings(max size 4KB) of data that are stored directly in the browser.
  • They are a part of the HTTP protocol, defined by the RFC 6265 specification
  • Sent to server on ecah request
  • Cookies are usually set by a web-server using the response Set-Cookie HTTP-header.
  • One cookie must not exceed 4KB, 20+ cookies per site(depends on the browser)

Why Cookies?

  • Cookies were invented to solve the problem how to remember information about the user
  • When a user visits a web page, his/her name can be stored in a cookie.
  • Next time the user visits the page, the cookie remembers his/her name.

Read cookies

  • The value of document.cookie consists of name=value pairs, delimited by ;
  • Each one is a separate cookie.
// show all cookies
document.cookie 

// cookie1=value1; cookie2=value2;...
function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(';').shift();
}

Create/Update cookies

  • It updates/sets cookies only that are mentioned,
  • It does not overwrite other cookies
// update/create only cookie named 'user'
document.cookie = "user=John";

Delete a cookies

  • Deleting a cookie is very simple.
  • You don’t have to specify a cookie value when you delete a cookie.
  • Just set the expires parameter to a past date:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

Important key-value pair used in cookies

path=/mypath in cookies

document.cookie = "user=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"
  • If a cookie is set with path=/admin,
  • It’s visible at pages /admin and /admin/something
  • But not at /home or /adminpage.

domain=site.com in cookies

  • A domain defines where the cookie is accessible.
  • Domain1 cookies are only acessible at Domain1 only
  • But can set cookies for other domain
// At site.com --> make the cookie accessible on any subdomain *.site.com:
document.cookie = "user=John; domain=site.com"

// At forum.site.com
alert(document.cookie); // has cookie user=John

expires=Tue, 19 Jan 2038 03:14:07 GMT in cookies

  • By default, if a cookie doesn’t have expires or max-age, it disappears when the browser is closed
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
  • Delete session survived cookie
    • If we set expires to a date in the past,
    • Then the browser will automatically delete it.

max-age=3600 in cookies

  • Is an alternative to expires,
  • Specifies the cookie’s expiration in seconds from the current moment.
// cookie will die in +1 hour from now
document.cookie = "user=John; max-age=3600";

// delete cookie (let it expire right now)
document.cookie = "user=John; max-age=0";

secure in session

  • Used when cookie is sensitive and should be transferred only over HTTPS.
  • Cookies are domain-based, they do not distinguish between the protocols
// set the cookie to be secure (only accessible over HTTPS)
document.cookie = "user=John; secure";

samesite or samesite=strict in cookies

  • It’s designed to protect from so-called XSRF (cross-site request forgery) attacks.
  • Eg:
    • Attacker1 copy cookies from User1(say back data)
    • Attacker1 pretends to be User1 and request banks
    • This is called XSRF attack
  • XSRF protection token is used by bank to safeguard this problem

httpOnly in cookies

  • The web-server uses the Set-Cookie header to set a cookie.
  • If httpOnly option is set then
    • It forbids any JavaScript access to the cookie
    • We can’t see such a cookie or manipulate it using document.cookie

Web Storage

  • Web storage objects localStorage and sessionStorage allow to save key/value pairs in the browser.
  • Key/value pairs are always stored as strings

Why additional objects?

  • Web storage objects are not sent to server with each request.
  • Most browsers allow at least 2 megabytes of data (or more)
  • The storage is bound to the origin

Both storage objects provide same methods and properties:

  • setItem(key, value)
    • store key/value pair.
  • getItem(key)
    • get the value by key.
  • removeItem(key)
    • remove the key with its value.
  • clear()
    • delete everything.
  • key(index)
    • get the key on a given position.
  • length
    • the number of stored items.

localStorage

  • Shared between all tabs and windows from the same origin.
  • Stores data with no expiration date.
  • It remains after the browser restart and even OS reboot

Set local storage item

localStorage.setItem('test', 1);
localStorage.setItem('name', 'John');

localStorage.lastname = "Smith";

Get from storage

localStorage.getItem('test');
localStorage.lastname;

// get all stored data
localStorage;

Clear local storage

localStorage.clear();

Remove key

delete localStorage.test;

Loop over

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

Store and access JSON/dict in localsesion

localStorage.user = {name: "John"};
localStorage.user 
//OP: '[object Object]'

localStorage.user = JSON.stringify({name: "John"});
localStorage.user
// OP: '{"name":"John"}'

JSON.parse( localStorage.user );
// OP: {name: 'John'}

sessionStorage

  • The sessionStorage object is used much less often than localStorage.
  • The sessionStorage exists only within the current browser tab.
    • It is bound not only to the origin, but also to the browser tab
  • The data is stored for only one session.
  • It survives page refresh, but not closing/opening the tab.
sessionStorage.setItem('test', 1);

sessionStorage.getItem('test')

NOTE

  • When the data gets updated in localStorage or sessionStorage, storage event triggers, with properties:
    • key – the key that was changed (null if .clear() is called).
    • oldValue – the old value (null if the key is newly added).
    • newValue – the new value (null if the key is removed).
    • url – the url of the document where the update happened.
    • storageArea – either localStorage or sessionStorage object where the update happened.
  • Storage event Triggers on
    • setItem, removeItem, clear call.
  • The storage event triggers on all window
    • localStorage is shared between different tabs
    • Stotage event on 1-tab will also affect all-tabs
    • if they are listening i.e storage eventis used
window.onstorage = event => {}
window.addEventListener('storage', event => {}
window.onstorage = event => {
  alert(event.url);
};
localStorage.setItem('user', 1);

localStorage(), window.localStorage(), or document.localStorage()?

  • Unless you’ve declared a variable named localStorage in a custom defined scope, they’re the same.
  • localStorage refers to window.localStorage.
  • In fact every variable in global namespace can be accessed

Reference