How to Set & Read Javascript Cookies

A tutorial on how to set and read javascript cookies

Rob Johnson

By Rob Johnson

Sat Sep 05 2015

#javascript

Here are a few tricks with javascript that can be adapted for many uses. That said, the users browser will need to have javascript enabled. The following code doesn't require jQuery.

Step 1: Create a cookie

document.cookie="cookiename=cookievalue";

Step 2: Initial script to allow you to read cookies

var cookies;

function readCookie(name,c,C,i){
  if(cookies){ return cookies[name]; }

  c = document.cookie.split('; ');
  cookies = {};

  for(i=c.length-1; i>=0; i--){
    C = c[i].split('=');
    cookies[C[0]] = C[1];
  }

  return cookies[name];
}

window.readCookie = readCookie; // or expose it however you want

Step 3: Request the value of a specific cookie

readCookie("cookiename");
# commerce 14 # seo 5 # tools 6 # amazon 1 # sql 4 # shopify 9 # javascript 13 # projects 4 # css 2 # git 2 # php 3 # analytics 4 # api 6 # monitoring 2 # python 2 # aws 2