What is the shortest function for reading a cookie by name in JavaScript?

JavascriptCookies

Javascript Problem Overview


What is the shortest, accurate, and cross-browser compatible method for reading a cookie in JavaScript?

Very often, while building stand-alone scripts (where I can't have any outside dependencies), I find myself adding a function for reading cookies, and usually fall-back on the QuirksMode.org readCookie() method (280 bytes, 216 minified.)

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

It does the job, but its ugly, and adds quite a bit of bloat each time.

The method that jQuery.cookie uses something like this (modified, 165 bytes, 125 minified):

function read_cookie(key)
{
	var result;
	return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? (result[1]) : null;
}

Note this is not a 'Code Golf' competition: I'm legitimately interested in reducing the size of my readCookie function, and in ensuring the solution I have is valid.

Javascript Solutions


Solution 1 - Javascript

Shorter, more reliable and more performant than the current best-voted answer:

const getCookieValue = (name) => (
  document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() || ''
)

A performance comparison of various approaches is shown here:

https://jsben.ch/AhMN6

Some notes on approach:

The regex approach is not only the fastest in most browsers, it yields the shortest function as well. Additionally it should be pointed out that according to the official spec (RFC 2109), the space after the semicolon which separates cookies in the document.cookie is optional and an argument could be made that it should not be relied upon. Additionally, whitespace is allowed before and after the equals sign (=) and an argument could be made that this potential whitespace should be factored into any reliable document.cookie parser. The regex above accounts for both of the above whitespace conditions.

Solution 2 - Javascript

This will only ever hit document.cookie ONE time. Every subsequent request will be instant.

(function(){
    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
})();

I'm afraid there really isn't a faster way than this general logic unless you're free to use .forEach which is browser dependent (even then you're not saving that much)

Your own example slightly compressed to 120 bytes:

function read_cookie(k,r){return(r=RegExp('(^|; )'+encodeURIComponent(k)+'=([^;]*)').exec(document.cookie))?r[2]:null;}

You can get it to 110 bytes if you make it a 1-letter function name, 90 bytes if you drop the encodeURIComponent.

I've gotten it down to 73 bytes, but to be fair it's 82 bytes when named readCookie and 102 bytes when then adding encodeURIComponent:

function C(k){return(document.cookie.match('(^|; )'+k+'=([^;]*)')||0)[2]}

Solution 3 - Javascript

Assumptions

Based on the question, I believe some assumptions / requirements for this function include:

  • It will be used as a library function, and so meant to be dropped into any codebase;
  • As such, it will need to work in many different environments, i.e. work with legacy JS code, CMSes of various levels of quality, etc.;
  • To inter-operate with code written by other people and/or code that you do not control, the function should not make any assumptions on how cookie names or values are encoded. Calling the function with a string "foo:bar[0]" should return a cookie (literally) named "foo:bar[0]";
  • New cookies may be written and/or existing cookies modified at any point during lifetime of the page.

Under these assumptions, it's clear that encodeURIComponent / decodeURIComponent should not be used; doing so assumes that the code that set the cookie also encoded it using these functions.

The regular expression approach gets problematic if the cookie name can contain special characters. jQuery.cookie works around this issue by encoding the cookie name (actually both name and value) when storing a cookie, and decoding the name when retrieving a cookie. A regular expression solution is below.

Unless you're only reading cookies you control completely, it would also be advisable to read cookies from document.cookie directly and not cache the results, since there is no way to know if the cache is invalid without reading document.cookie again.

(While accessing and parsing document.cookies will be slightly slower than using a cache, it would not be as slow as reading other parts of the DOM, since cookies do not play a role in the DOM / render trees.)


Loop-based function

Here goes the Code Golf answer, based on PPK's (loop-based) function:

function readCookie(name) {
    name += '=';
    for (var ca = document.cookie.split(/;\s*/), i = ca.length - 1; i >= 0; i--)
        if (!ca[i].indexOf(name))
            return ca[i].replace(name, '');
}

which when minified, comes to 128 characters (not counting the function name):

function readCookie(n){n+='=';for(var a=document.cookie.split(/;\s*/),i=a.length-1;i>=0;i--)if(!a[i].indexOf(n))return a[i].replace(n,'');}

Regular expression-based function

Update: If you really want a regular expression solution:

function readCookie(name) {
    return (name = new RegExp('(?:^|;\\s*)' + ('' + name).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)').exec(document.cookie)) && name[1];
}

This escapes any special characters in the cookie name before constructing the RegExp object. Minified, this comes to 134 characters (not counting the function name):

function readCookie(n){return(n=new RegExp('(?:^|;\\s*)'+(''+n).replace(/[-[\]{}()*+?.,\\^$|#\s]/g,'\\$&')+'=([^;]*)').exec(document.cookie))&&n[1];}

As Rudu and cwolves have pointed out in the comments, the regular-expression-escaping regex can be shortened by a few characters. I think it would be good to keep the escaping regex consistent (you may be using it elsewhere), but their suggestions are worth considering.


Notes

Both of these functions won't handle null or undefined, i.e. if there is a cookie named "null", readCookie(null) will return its value. If you need to handle this case, adapt the code accordingly.

Solution 4 - Javascript

code from google analytics ga.js

function c(a){
    var d=[],
        e=document.cookie.split(";");
    a=RegExp("^\\s*"+a+"=\\s*(.*?)\\s*$");
    for(var b=0;b<e.length;b++){
        var f=e[b].match(a);
        f&&d.push(f[1])
    }
    return d
}

Solution 5 - Javascript

How about this one?

function getCookie(k){var v=document.cookie.match('(^|;) ?'+k+'=([^;]*)(;|$)');return v?v[2]:null}

Counted 89 bytes without the function name.

Solution 6 - Javascript

The following function will allow differentiating between empty strings and undefined cookies. Undefined cookies will correctly return undefined and not an empty string unlike some of the other answers here.

function getCookie(name) {
    return (document.cookie.match('(^|;) *'+name+'=([^;]*)')||[])[2];
}

The above worked fine for me on all browsers I checked, but as mentioned by @vanovm in comments, as per the specification the key/value may be surrounded by whitespace. Hence the following is more standard compliant.

function getCookie(name) {
    return (document.cookie.match('(?:^|;)\\s*'+name.trim()+'\\s*=\\s*([^;]*?)\\s*(?:;|$)')||[])[1];
}

Solution 7 - Javascript

Here goes.. Cheers!

function getCookie(n) {
    let a = `; ${document.cookie}`.match(`;\\s*${n}=([^;]+)`);
    return a ? a[1] : '';
}

Note that I made use of ES6's template strings to compose the regex expression.

Solution 8 - Javascript

this in an object that you can read, write, overWrite and delete cookies.

var cookie = {
    write : function (cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays*24*60*60*1000));
        var expires = "expires="+d.toUTCString();
        document.cookie = cname + "=" + cvalue + "; " + expires;
    },
    read : function (name) {
        if (document.cookie.indexOf(name) > -1) {
            return document.cookie.split(name)[1].split("; ")[0].substr(1)
        } else {
            return "";
        }
    },
    delete : function (cname) {
        var d = new Date();
        d.setTime(d.getTime() - 1000);
        var expires = "expires="+d.toUTCString();
        document.cookie = cname + "=; " + expires;
    }
};

Solution 9 - Javascript

Both of these functions look equally valid in terms of reading cookie. You can shave a few bytes off though (and it really is getting into Code Golf territory here):

function readCookie(name) {
    var nameEQ = name + "=", ca = document.cookie.split(';'), i = 0, c;
    for(;i < ca.length;i++) {
        c = ca[i];
        while (c[0]==' ') c = c.substring(1);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length);
    }
    return null;
}

All I did with this is collapse all the variable declarations into one var statement, removed the unnecessary second arguments in calls to substring, and replace the one charAt call into an array dereference.

This still isn't as short as the second function you provided, but even that can have a few bytes taken off:

function read_cookie(key)
{
    var result;
    return (result = new RegExp('(^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? result[2] : null;
}

I changed the first sub-expression in the regular expression to be a capturing sub-expression, and changed the result[1] part to result[2] to coincide with this change; also removed the unnecessary parens around result[2].

Solution 10 - Javascript

To truly remove as much bloat as possible, consider not using a wrapper function at all:

try {
	var myCookie = document.cookie.match('(^|;) *myCookie=([^;]*)')[2]
} catch (_) {
	// handle missing cookie
}

As long as you're familiar with RegEx, that code is reasonably clean and easy to read.

Solution 11 - Javascript

To have all cookies accessible by name in a Map:

const cookies = "a=b ; c = d ;e=";
const map = cookies.split(";").map((s) => s.split("=").map((s) => s.trim())).reduce((m, [k, v]) => (m.set(k, v), m), new Map());
console.log(map); //Map(3) {'a' => 'b', 'c' => 'd', 'e' => ''}
map.get("a"); //returns "b"
map.get("c"); //returns "d"
map.get("e"); //returns ""

Solution 12 - Javascript

(edit: posted the wrong version first.. and a non-functional one at that. Updated to current, which uses an unparam function that is much like the second example.)

Nice idea in the first example cwolves. I built on both for a fairly compact cookie reading/writing function that works across multiple subdomains. Figured I'd share in case anyone else runs across this thread looking for that.

(function(s){
  s.strToObj = function (x,splitter) {
    for ( var y = {},p,a = x.split (splitter),L = a.length;L;) {
      p = a[ --L].split ('=');
      y[p[0]] = p[1]
    }
    return y
  };
  s.rwCookie = function (n,v,e) {
    var d=document,
        c= s.cookies||s.strToObj(d.cookie,'; '),
        h=location.hostname,
        domain;
    if(v){
      domain = h.slice(h.lastIndexOf('.',(h.lastIndexOf('.')-1))+1);
      d.cookie = n + '=' + (c[n]=v) + (e ? '; expires=' + e : '') + '; domain=.' + domain + '; path=/'
    }
    return c[n]||c
  };
})(some_global_namespace)
  • If you pass rwCookie nothing, it will get all cookies into cookie storage
  • Passed rwCookie a cookie name, it gets that cookie's value from storage
  • Passed a cookie value, it writes the cookie and places the value in storage
  • Expiration defaults to session unless you specify one

Solution 13 - Javascript

Using cwolves' answer, but not using a closure nor a pre-computed hash :

// Golfed it a bit, too...
function readCookie(n){
  var c = document.cookie.split('; '),
      i = c.length,
      C;
  
  for(; i>0; i--){
     C = c[i].split('=');
     if(C[0] == n) return C[1];
  }
}

...and minifying...

function readCookie(n){var c=document.cookie.split('; '),i=c.length,C;for(;i>0;i--){C=c[i].split('=');if(C[0]==n)return C[1];}}

...equals 127 bytes.

Solution 14 - Javascript

Here is the simplest solution using javascript string functions.

document.cookie.substring(document.cookie.indexOf("COOKIE_NAME"), 
                          document.cookie.indexOf(";", 
                          document.cookie.indexOf("COOKIE_NAME"))).
  substr(COOKIE_NAME.length);

Solution 15 - Javascript

Just to throw my hat in the race, here's my proposal:

function getCookie(name) {
   const cookieDict = document.cookie.split(';')
        .map((x)=>x.split('='))
        .reduce((accum,current) => { accum[current[0]]=current[1]; return accum;}, Object());
    return cookieDict[name];
}

The above code generates a dict that stores cookies as key-value pairs (i.e., cookieDict), and afterwards accesses the property name to retrieve the cookie.

This could effectively be expressed as a one-liner, but this is only for the brave:

document.cookie.split(';').map((x)=>x.split('=')).reduce((accum,current) => { accum[current[0]]=current[1]; return accum;}, {})[name]

The absolute best approach would be to generate cookieDict at page load and then throughout the page lifecycle just access individual cookies by calling cookieDict['cookiename'].

Solution 16 - Javascript

This function doesn't work for older browser like chrome > 80.

const getCookieValue = (name) => (
  document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() || ''
)

I solved it by using this function instead that returns undefined if the cookie is missing:

function getCookie(name) {
  // Add the = sign
  name = name + '=';

  // Get the decoded cookie
  var decodedCookie = decodeURIComponent(document.cookie);

  // Get all cookies, split on ; sign
  var cookies = decodedCookie.split(';');

  // Loop over the cookies
  for (var i = 0; i < cookies.length; i++) {
    // Define the single cookie, and remove whitespace
    var cookie = cookies[i].trim();

    // If this cookie has the name of what we are searching
    if (cookie.indexOf(name) == 0) {
      // Return everything after the cookies name
      return cookie.substring(name.length, cookie.length);
    }
  }
}

Credit: https://daily-dev-tips.com/posts/vanilla-javascript-cookies-%F0%9F%8D%AA/

Solution 17 - Javascript

You can verify if a cookie exists and it has a defined value:

function getCookie(cookiename) {
    if (typeof(cookiename) == 'string' && cookiename != '') {
	    const COOKIES = document.cookie.split(';');
	    for (i = 0; i < COOKIES.length; i++) {
		    if (COOKIES[i].trim().startsWith(cookiename)) {
			    return COOKIES[i].split('=')[1];
		    }
	    }
    }

    return null;
}

const COOKIE_EXAMPLE = getCookie('example');
if (COOKIE_EXAMPLE == 'stackoverflow') { ... }
// If is set a cookie named "example" with value "stackoverflow"
if (COOKIE_EXAMPLE != null) { ... }
// If is set a cookie named "example" ignoring the value

It will return null if cookie doesn't exists.

Solution 18 - Javascript

It's 2022, everything except Internet Explorer supports the URLSearchParams API (^1) and String.prototype.replaceAll API (^2), so we can horribly (ab)use them:

const cookies = new URLSearchParams(document.cookie.replaceAll('&', '%26').replaceAll('; ', '&'));
cookies.get('cookie name'); // returns undefined if not set, string otherwise

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYahelView Question on Stackoverflow
Solution 1 - JavascriptMacView Answer on Stackoverflow
Solution 2 - JavascriptNoneView Answer on Stackoverflow
Solution 3 - JavascriptJeffery ToView Answer on Stackoverflow
Solution 4 - JavascriptChicoDeFeView Answer on Stackoverflow
Solution 5 - JavascriptSimon SteinbergerView Answer on Stackoverflow
Solution 6 - JavascriptJoyce BabuView Answer on Stackoverflow
Solution 7 - JavascriptmfaladeView Answer on Stackoverflow
Solution 8 - Javascriptuser4868160View Answer on Stackoverflow
Solution 9 - JavascriptJeff AvalloneView Answer on Stackoverflow
Solution 10 - JavascriptAbhi BeckertView Answer on Stackoverflow
Solution 11 - JavascriptgogoView Answer on Stackoverflow
Solution 12 - JavascriptAdamView Answer on Stackoverflow
Solution 13 - JavascriptFélix SaparelliView Answer on Stackoverflow
Solution 14 - JavascriptKumarView Answer on Stackoverflow
Solution 15 - JavascriptRAMView Answer on Stackoverflow
Solution 16 - JavascriptT. SmithView Answer on Stackoverflow
Solution 17 - JavascriptMarco ConcasView Answer on Stackoverflow
Solution 18 - JavascriptHenryView Answer on Stackoverflow