Javascript: Basic cookie usage 🍪

You set a cookie by document.cookie = "name=value". You set another similarly document.cookie = "name1=value1". And then document.cookie's value is:

name=value; name1=value1

You probably want to get an individual cookie from a dictionary. You'll need to split and map and reduce for that.

function get_cookies() {
  return document.cookie.split(";")
  .map(cookie => cookie.split("="))
  .reduce((acc, value) =>
    ( acc[value[0].trim()] = value[1].trim(), acc ),

(Also also probably want to decode the value with decodeURIComponent but I haven't for brevity)

You have a SameSite property on a cookie. Your browser will complain if you don't set this. It's to prevent cross site scripting attacks. It specifies when a cookie is sent to the server.

  • None with all requests
  • Lax only with request that are initiated by a url click, for example
  • Strict only from the cookie-issuing site.

You should read up on this at Mozilla.

document.cookie = "name=value; SameSite=Strict"

More to come, probs, including how to delete them, which involves setting the expiration date.

javascript cookies
I've removed disqus comments
Instead, press this
to express thanks
So far, 0 people have pressed the octopus