How do I create and read a value from cookie?

How can I create and read a value from a cookie in JavaScript?


Here are functions you can use for creating and retrieving cookies.

function createCookie(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

Minimalistic and full featured ES6 approach:

const setCookie = (name, value, days = 7, path = '/') => {
  const expires = new Date(Date.now() + days * 864e5).toUTCString()
  document.cookie = name + '=' + encodeURIComponent(value) + '; expires=' + expires + '; path=' + path
}

const getCookie = (name) => {
  return document.cookie.split('; ').reduce((r, v) => {
    const parts = v.split('=')
    return parts[0] === name ? decodeURIComponent(parts[1]) : r
  }, '')
}

const deleteCookie = (name, path) => {
  setCookie(name, '', -1, path)
}

JQuery Cookies

or plain Javascript:

function setCookie(c_name,value,exdays)
{
   var exdate=new Date();
   exdate.setDate(exdate.getDate() + exdays);
   var c_value=escape(value) + ((exdays==null) ? "" : ("; expires="+exdate.toUTCString()));
   document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
   var i,x,y,ARRcookies=document.cookie.split(";");
   for (i=0; i<ARRcookies.length; i++)
   {
      x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
      y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
      x=x.replace(/^\s+|\s+$/g,"");
      if (x==c_name)
      {
        return unescape(y);
      }
   }
}

ES7, using a regex for get(). Based on MDN

const Cookie = {
    get: name => {
        let c = document.cookie.match(`(?:(?:^|.*; *)${name} *= *([^;]*).*$)|^.*$`)[1]
        if (c) return decodeURIComponent(c)
    },
    set: (name, value, opts = {}) => {
        /*If options contains days then we're configuring max-age*/
        if (opts.days) {
            opts['max-age'] = opts.days * 60 * 60 * 24;

            /*Deleting days from options to pass remaining opts to cookie settings*/
            delete opts.days 
        }

        /*Configuring options to cookie standard by reducing each property*/
        opts = Object.entries(opts).reduce(
            (accumulatedStr, [k, v]) => `${accumulatedStr}; ${k}=${v}`, ''
        )

        /*Finally, creating the key*/
        document.cookie = name + '=' + encodeURIComponent(value) + opts
    },
    delete: (name, opts) => Cookie.set(name, '', {'max-age': -1, ...opts}) 
    // path & domain must match cookie being deleted 
}

Cookie.set('user', 'Jim', {path: '/', days: 10}) 
// Set the path to top level (instead of page) and expiration to 10 days (instead of session)

Usage - Cookie.get(name, value [, options]):
options supports all standard cookie options and adds "days":

  • path: '/' - any absolute path. Default: current document location,
  • domain: 'sub.example.com' - may not start with dot. Default: current host without subdomain.
  • secure: true - Only serve cookie over https. Default: false.
  • days: 2 - days till cookie expires. Default: End of session.
    Alternative ways of setting expiration:
    • expires: 'Sun, 18 Feb 2018 16:23:42 GMT' - date of expiry as a GMT string.
      Current date can be gotten with: new Date(Date.now()).toUTCString()
    • 'max-age': 30 - same as days, but in seconds instead of days.

Other answers use "expires" instead of "max-age" to support older IE versions. This method requires ES7, so IE7 is out anyways (this is not a big deal).

Note: Funny characters such as "=" and "{:}" are supported as cookie values, and the regex handles leading and trailing whitespace (from other libs).
If you would like to store objects, either encode them before and after with and JSON.stringify and JSON.parse, edit the above, or add another method. Eg:

Cookie.getJSON = name => JSON.parse(Cookie.get(name))
Cookie.setJSON = (name, value, opts) => Cookie.set(name, JSON.stringify(value), opts);

Mozilla created a simple framework for reading and writing cookies with full unicode support along with examples of how to use it.

Once included on the page, you can set a cookie:

docCookies.setItem(name, value);

read a cookie:

docCookies.getItem(name);

or delete a cookie:

docCookies.removeItem(name);

For example:

// sets a cookie called 'myCookie' with value 'Chocolate Chip'
docCookies.setItem('myCookie', 'Chocolate Chip');

// reads the value of a cookie called 'myCookie' and assigns to variable
var myCookie = docCookies.getItem('myCookie');

// removes the cookie called 'myCookie'
docCookies.removeItem('myCookie');

See more examples and details on Mozilla's document.cookie page.

A version of this simple js file is on github.