135

What's a good way to check if a cookie exist?

Conditions:

Cookie exists if

cookie1=;cookie1=345534;
//or
cookie1=345534;cookie1=;
//or
cookie1=345534;

Cookie doesn't exist if

cookie=;
//or
<blank>
Edric
  • 24,639
  • 13
  • 81
  • 91
confuzzled
  • 1,353
  • 2
  • 9
  • 4

22 Answers22

163

You can call the function getCookie with the name of the cookie you want, then check to see if it is = null.

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
        var end = document.cookie.indexOf(";", begin);
        if (end == -1) {
        end = dc.length;
        }
    }
    // because unescape has been deprecated, replaced with decodeURI
    //return unescape(dc.substring(begin + prefix.length, end));
    return decodeURI(dc.substring(begin + prefix.length, end));
} 

function doSomething() {
    var myCookie = getCookie("MyCookie");

    if (myCookie == null) {
        // do cookie doesn't exist stuff;
    }
    else {
        // do cookie exists stuff
    }
}
jac
  • 9,666
  • 2
  • 34
  • 63
  • 3
    Since `unescape` is deprecated, is there any difference using `decodeURIComponent` instead? – the_nuts Aug 10 '16 at 08:27
  • 3
    @the_nuts, Nice catch. I didn't know this. According to w3cschools decodeURI(), or decodeURIComponent can be used to replace unescape. Choice of which to use might come down to what is being stored, I chose decodeURI because I don't expect to have encoded separator characters in the cookie. Full reference: http://www.w3schools.com/jsref/jsref_decodeuri.asp – jac Aug 10 '16 at 14:40
  • 4
    this does not work with the first cookie because variable end is not set – warch Jul 04 '18 at 13:47
  • function doSomething($name) { var myCookie = getCookie($name); – Sol Mar 29 '19 at 16:11
  • 4
    This is a perfect example of why w3schools is not a reliable source and why you shouldn't copy/paste answers from it. You would have avoided using == and != which is fairly well known in js. – Isaac Pak May 28 '19 at 13:47
  • Is there a way in expressjs? – Spacehold Apr 18 '21 at 14:24
  • Will this work for httpOnly cookie? We'd need to check for existence from server, right? – alchemist95 Aug 22 '23 at 04:15
136

I have crafted an alternative non-jQuery version:

document.cookie.match(/^(.*;)?\s*MyCookie\s*=\s*[^;]+(.*)?$/)

It only tests for cookie existence. A more complicated version can also return cookie value:

value_or_null = (document.cookie.match(/^(?:.*;)?\s*MyCookie\s*=\s*([^;]+)(?:.*)?$/)||[,null])[1]

Put your cookie name in in place of MyCookie.

hegemon
  • 6,614
  • 2
  • 32
  • 30
  • 24
    wonderful clean solution! People grab plugins way too quickly these days... too much overhead. This is a very nice solution! – patrick Apr 25 '15 at 10:34
  • 3
    This doesn't work. Regex is missing a space. It should be document.cookie.match(/^(.*;)? MyCookie=[^;]+(.*)?$/), notice the space after ?. – Bogdan M. Nov 01 '16 at 12:18
  • 1
    document.cookie returns cookies separated by spaces, i.e.: cookie1= ; cookie1=345534; – Bogdan M. Nov 01 '16 at 12:20
  • Warning: it doesn't work. There is an *optional* whitespace before the cookie's name. Prefer /^(.*;)?[ ]{0,1}MyCookie=[^;]+(.*)?$/ – Gabriel Mar 10 '17 at 08:26
  • 1
    @BogdanM. : There is not white space for the first cookie ! /[ ]{0,1}/ See my comment above – Gabriel Mar 10 '17 at 08:27
  • @Gabriel Thank you for pointing this out. Check out the updated answer – hegemon Mar 13 '17 at 08:24
  • 7
    If you want to use a variable: new RegExp("^(?:.*;)?\\s*" + cookieName + "\\s*=\\s*([^;]+)(?:.*)?$") – josef Jun 14 '17 at 10:48
  • Doesn't work for me. Is it because there is a `-` in my cookie's name? Escaping it with a backslash doesn't change anything (besides eslint showing me a warning that this is an unnecessary escape) Edit: Apparently this does not work for `httpOnly` cookies. – Florian Walther Mar 21 '22 at 09:17
63
document.cookie.indexOf('cookie_name=');

It will return -1 if that cookie does not exist.

p.s. Only drawback of it is (as mentioned in comments) that it will mistake if there is cookie set with such name: any_prefix_cookie_name

(Source)

Community
  • 1
  • 1
HackToHell
  • 2,223
  • 5
  • 29
  • 44
  • 9
    This also matches any cookies with the string in their name. E.g. the example returns something other than `-1` if `cookie_name_whatever` is set (even if cookie_name is not). The regex version in another answer solves that. – hajamie Jan 05 '17 at 13:25
  • 7
    While not 100% accurate, this is a good enough solution in most cases. Thanks for this - I feel much more comfortable using this than a large function, or complicated regexp from the other solutions. – Shane N Jan 25 '18 at 19:05
  • @hajamie I think using `document.cookie.indexOf('cookie_name=') == 0;` solves that problem. True only if the cookie starts with the mentioned text, false otherwise. – Lasse Jacobs Jul 18 '21 at 15:11
  • 2
    @Lasse, only if that's the only cookie you have (or it's the first). [document.cookie](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) contains a semicolon-separated list of all cookies. – hajamie Jul 20 '21 at 15:38
20

This is an old question, but here's the approach I use ...

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

This returns null either when the cookie doesn't exist, or when it doesn't contain the requested name.
Otherwise, the value (of the requested name) is returned.

A cookie should never exist without a value -- because, in all fairness, what's the point of that?
If it's no longer needed, it's best to just get rid of it all together.

function deleteCookie(name) {
    document.cookie = name +"=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
}
Dustin Halstead
  • 741
  • 6
  • 19
  • 2
    There is a perfectly valid reason for having a cookie without a value, that is to signal the existence of something. It would be used like a Boolean: cookie exists => true, cookie does not exist => false – Gus Jan 06 '20 at 17:29
  • 4
    This was the best method in the list. – Andrew Mar 04 '20 at 09:45
  • 2
    Why aren't functions like this just built in for us? Netscape 0.9b from 26.3 years ago had cookies - getting and setting them doesn't appear to have meaningfully improved in the 2.5 decades since despite all the ECMA versions put out. – ArtOfWarfare Feb 23 '21 at 00:42
  • 2
    You can further simplify the `getCookie` function by `return match && match[1];` As this will return `null` when `match` is not a "positive" condition. – lbragile Mar 10 '21 at 04:59
17

ATTENTION! the chosen answer contains a bug (Jac's answer).

if you have more than one cookie (very likely..) and the cookie you are retrieving is the first on the list, it doesn't set the variable "end" and therefore it will return the entire string of characters following the "cookieName=" within the document.cookie string!

here is a revised version of that function:

function getCookie( name ) {
    var dc,
        prefix,
        begin,
        end;
    
    dc = document.cookie;
    prefix = name + "=";
    begin = dc.indexOf("; " + prefix);
    end = dc.length; // default to end of the string

    // found, and not in first position
    if (begin !== -1) {
        // exclude the "; "
        begin += 2;
    } else {
        //see if cookie is in first position
        begin = dc.indexOf(prefix);
        // not found at all or found as a portion of another cookie name
        if (begin === -1 || begin !== 0 ) return null;
    } 

    // if we find a ";" somewhere after the prefix position then "end" is that position,
    // otherwise it defaults to the end of the string
    if (dc.indexOf(";", begin) !== -1) {
        end = dc.indexOf(";", begin);
    }

    return decodeURI(dc.substring(begin + prefix.length, end) ).replace(/\"/g, ''); 
}
TheKojuEffect
  • 20,103
  • 19
  • 89
  • 125
AndPicc
  • 183
  • 1
  • 8
  • With just one cookie set, your function returned "cookieName=". :-/ – Jeppe Jul 19 '18 at 12:50
  • 1
    @Jeppe I have modified the code to work when there is only one cookie as well. I've actually took the chance to refactor the whole function and tidy it up, as well as adding some comments. ;) – AndPicc Jul 20 '18 at 19:44
  • there is something wrong with replace(/"/g, ''); it gives me syntax error – zEn feeLo Mar 12 '19 at 07:59
  • it worked for me but probably it's better to escape the quotes in the regex. I have edited the answer. Should work for you too now! – AndPicc Mar 13 '19 at 08:52
6

If you're using jQuery, you can use the jquery.cookie plugin.

Getting the value for a particular cookie is done as follows:

$.cookie('MyCookie'); // Returns the cookie value
Mark Amery
  • 143,130
  • 81
  • 406
  • 459
HeWhoProtects
  • 477
  • 1
  • 10
  • 21
  • 3
    This also assumes OP is using the jquery-cookie plugin. It threw me for a loop for a bit since I was using jquery but can't use that plugin for the task I was solving for. – hippeelee Apr 16 '13 at 16:12
  • 8
    this is not only specific to jquery but also requires a jquery plugin which you did not reference in your answer – artfulhacker May 22 '13 at 17:12
  • 1
    I'm genuinely amazed in 2021 Javascript doesn't come with a simple way of testing for a cookie like this with a built in method where you can add the cookie's name as a parameter. What an odd and silly language JS is at times. – pjk_ok Mar 26 '21 at 18:47
5

regexObject.test( String ) is faster than string.match( RegExp ).

The MDN site describes the format for document.cookie, and has an example regex to grab a cookie (document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");). Based on that, I'd go for this:

/^(.*;)?\s*cookie1\s*=/.test(document.cookie);

The question seems to ask for a solution which returns false when the cookie is set, but empty. In that case:

/^(.*;)?\s*cookie1\s*=\s*[^;]/.test(document.cookie);

Tests

function cookieExists(input) {return /^(.*;)?\s*cookie1\s*=/.test(input);}
function cookieExistsAndNotBlank(input) {return /^(.*;)?\s*cookie1\s*=\s*[^;]/.test(input);}
var testCases = ['cookie1=;cookie1=345534;', 'cookie1=345534;cookie1=;', 'cookie1=345534;', ' cookie1 = 345534; ', 'cookie1=;', 'cookie123=345534;', 'cookie=345534;', ''];
console.table(testCases.map(function(s){return {'Test String': s, 'cookieExists': cookieExists(s), 'cookieExistsAndNotBlank': cookieExistsAndNotBlank(s)}}));

Test results (Chrome 55.0.2883.87)

Community
  • 1
  • 1
hajamie
  • 2,848
  • 2
  • 22
  • 20
4

Note that if a cookie is secure, you cannot check in client side for its existence using document.cookie (which all of the answers are using). Such cookie can be checked only at sever side.

callback
  • 3,981
  • 1
  • 31
  • 55
  • 3
    I think you meant [http only](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies) cookies. Secure cookies are still accessible to the client. – carlin.scott Dec 28 '21 at 01:13
2

instead of the cookie variable you would just use document.cookie.split...

var cookie = 'cookie1=s; cookie1=; cookie2=test';
var cookies = cookie.split('; ');
cookies.forEach(function(c){
  if(c.match(/cookie1=.+/))
   console.log(true);
});
KFish
  • 440
  • 3
  • 9
2

There are several good answers here. I however prefer [1] not using a regular expression, and [2] using logic that is simple to read, and [3] to have a short function that [4] does not return true if the name is a substring of another cookie name . Lastly [5] we can't use a for each loop since a return doesn't break it.

function cookieExists(name) {
  var cks = document.cookie.split(';');
  for(i = 0; i < cks.length; i++)
    if (cks[i].split('=')[0].trim() == name) return true;
}
Fom
  • 485
  • 6
  • 14
1
function getCookie(name) {

    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
        else{
            var oneCookie = dc.indexOf(';', begin);
            if(oneCookie == -1){
                var end = dc.length;
            }else{
                var end = oneCookie;
            }
            return dc.substring(begin, end).replace(prefix,'');
        } 

    }
    else
    {
        begin += 2;
        var end = document.cookie.indexOf(";", begin);
        if (end == -1) {
            end = dc.length;
        }
        var fixed = dc.substring(begin, end).replace(prefix,'');
    }
    // return decodeURI(dc.substring(begin + prefix.length, end));
    return fixed;
} 

Tried @jac function, got some trouble, here's how I edited his function.

Matheus
  • 880
  • 1
  • 7
  • 13
1

For anyone using Node, I found a nice and simple solution with ES6 imports and the cookie module!

First install the cookie module (and save as a dependency):

npm install --save cookie

Then import and use:

import cookie from 'cookie';
let parsed = cookie.parse(document.cookie);
if('cookie1' in parsed) 
    console.log(parsed.cookie1);
jonny
  • 3,022
  • 1
  • 17
  • 30
1

Using Javascript:

 function getCookie(name) {
      let matches = document.cookie.match(new RegExp(
        "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
      ));
      return matches ? decodeURIComponent(matches[1]) : undefined;
    }
Ashish
  • 174
  • 2
  • 13
1
// check if cookie is present 
function is_CookiePresent( cookieName ){

  if( void 0 != cookieName && "" != cookieName && null != cookieName ){

    var is_present = document.cookie.split(";").filter(e=>{
        if(e.trim().split("=").includes(cookieName)) return true;
    })

    if(!is_present.length){return false;}
    return true;

  }
  else{
    return false;
  }

}

// Get cookie name value :) 
function getCookieValue( cookieName ){

  if( void 0 != cookieName && "" != cookieName && null != cookieName ){

    var is_present = document.cookie.split(";").filter(e=>{
        if(e.trim().split("=").includes(cookieName)) return true;
    })

    if(!is_present.length){return false;}
   
    var __CookieValue = is_present.join('').trim();

    return __CookieValue.substring(__CookieValue.indexOf('=')+1);

  }
  else{
    return false;
  }

}
0
function getcookie(name = '') {
    let cookies = document.cookie;
    let cookiestore = {};
    
    cookies = cookies.split(";");
    
    if (cookies[0] == "" && cookies[0][0] == undefined) {
        return undefined;
    }
    
    cookies.forEach(function(cookie) {
        cookie = cookie.split(/=(.+)/);
        if (cookie[0].substr(0, 1) == ' ') {
            cookie[0] = cookie[0].substr(1);
        }
        cookiestore[cookie[0]] = cookie[1];
    });
    
    return (name !== '' ? cookiestore[name] : cookiestore);
}

To get a object of cookies simply call getCookie()

To check if a cookie exists, do it like this:

if (!getcookie('myCookie')) {
    console.log('myCookie does not exist.');
} else {
    console.log('myCookie value is ' + getcookie('myCookie'));
}

Or just use a ternary operator.

0

Parse cookies with Array.prototype.reduce() into an object (ES6)

const cookies = document.cookie.split(";").reduce((e, t) => {
  const [c, n] = t.trim().split("=").map(decodeURIComponent);
  try { // this can be removed if you do not need JSON cookies parsed
    return Object.assign(e, {
      [c]: JSON.parse(n)
    })
  }
  catch (t) {
    return Object.assign(e, {
      [c]: n
    })
  }
}, {})

Check if your cookie is there

typeof cookies.yourCookie === "string";
undefined
  • 1,019
  • 12
  • 24
0

If anyone is still looking into this post maybe this will help.

First do a function to get the cookie, something like this..

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

Then you could check if the specific cookie exists before doing something else

if( getCookie(mycookieName)){
 // do something....
}
mackelele
  • 111
  • 7
-1

use this method instead:

function getCookie(name) {
    var value = "; " + document.cookie;
    var parts = value.split("; " + name + "=");
    if (parts.length == 2) return parts.pop().split(";").shift();
    else return null;
}

function doSomething() {
    var myCookie = getCookie("MyCookie");

    if (myCookie == null) {
        // do cookie doesn't exist stuff;
    }
    else {
        // do cookie exists stuff
    }
}
warch
  • 2,387
  • 2
  • 26
  • 43
-1
/// ************************************************ cookie_exists

/// global entry point, export to global namespace

/// <synopsis>
///   cookie_exists ( name );
///
/// <summary>
///   determines if a cookie with name exists
///
/// <param name="name">
///   string containing the name of the cookie to test for 
//    existence
///
/// <returns>
///   true, if the cookie exists; otherwise, false
///
/// <example>
///   if ( cookie_exists ( name ) );
///     {
///     // do something with the existing cookie
///     }
///   else
///     {
///     // cookies does not exist, do something else 
///     }

function cookie_exists ( name )
  {
  var exists = false;

  if ( document.cookie )
    {
    if ( document.cookie.length > 0 )
      {
                                    // trim name
      if ( ( name = name.replace ( /^\s*/, "" ).length > 0 ) )
        {
        var cookies = document.cookie.split ( ";" );
        var name_with_equal = name + "=";

        for ( var i = 0; ( i < cookies.length ); i++ )
          {
                                    // trim cookie
          var cookie = cookies [ i ].replace ( /^\s*/, "" );

          if ( cookie.indexOf ( name_with_equal ) === 0 )
            {
            exists = true;
            break;
            }
          }
        }
      }
    }

  return ( exists );

  } // cookie_exists
Gus
  • 1,383
  • 2
  • 12
  • 23
-1
function hasCookie(cookieName){
return document.cookie.split(';')
.map(entry => entry.split('='))
.some(([name, value]) => (name.trim() === cookieName) && !!value);
}

Note: The author wanted the function to return false if the cookie is empty i.e. cookie=; this is achieved with the && !!value condition. Remove it if you consider an empty cookie is still an existing cookie…

Flavien Volken
  • 19,196
  • 12
  • 100
  • 133
-1

var cookie = 'cookie1=s; cookie1=; cookie2=test';
var cookies = cookie.split('; ');
cookies.forEach(function(c){
  if(c.match(/cookie1=.+/))
   console.log(true);
});
  • Hello and welcome to SO! While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. Please read the [tour](https://stackoverflow.com/tour), and [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) – Tomer Shetah Dec 23 '20 at 10:18
-1

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.

Marco Concas
  • 1,665
  • 20
  • 25