How do I create and read a value from cookie with javascript?
Asked Answered
O

22

346

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

Osculate answered 28/1, 2011 at 6:58 Comment(3)
Quirks mode has a good guide to JavaScript and cookies.Penton
FWIW, js-cookie provides a very good API for handling it.Perturbation
Don't forget that the Web Storage API, could be a good alternative to cookies in some situations.Chipper
R
278

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 "";
}
Ripon answered 28/1, 2011 at 6:59 Comment(9)
This doesn't work if your cookie value contains anything that doesn't encode/decode well. The one at w3schools seems to work beautiflyRaines
This simple wrapper from Mozilla has explicit unicode support mentioned as wellCoquelicot
@BradParks Too bad it's released on GPL.Viviyan
This will not work on IE8 or 9 if the cookie does not have a value, because IE does not add the equal sign (=) after the cookie name. What we do is to check if indexOf("=")==-1, and if so use the entire cookie as the cookie name.Cattycornered
@Viviyan And I would say it is also in the public domain: developer.mozilla.org/en-US/docs/MDN/…Card
@Card might be, but it's not 100% clear. The documentation mentioned some older code being available under different licenses (but the block indicating that is no longer in use on the site). Another part mentioned forcing people contributing code to do so under public domain, but that part might have not been there where this particular code was added (I presume the code has been there for a while). In other words MDN has a bit of a mess in therms of licenses of older content, but one might as well pretend they don't and assume that everything is under PD or MIT.Viviyan
It fails. Returns a value for any ending substring of the key: setCookie('test', 'foo'); getCookie('est') -> 'foo'. It doesn't encode values: createCookie('test', 'foo; bar'); getCookie('test') -> 'foo'Intoxicant
Can anybody clarify why unescape is used in the getter, but escape is not used in the setter? Is unescape really needed? Should escape be added?Duchy
FYI, toGMTString() is deprecated: ReferenceDoorplate
M
74

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)
}
Michel answered 1/8, 2016 at 12:42 Comment(6)
Sometimes cookie value itself may contain = sign. In that case function getCookie will produce unexpected result. To avoid that consider using following arrow function body inside reduce const [n, ...val] = v.split('='); return n === name ? decodeURIComponent(val.join('=')) : rMartijn
Would be nice to have an option to leave the expiry date unset though. This would allow the cookie to be automatically deleted upon browser exit.Limitative
https://mcmap.net/q/55466/-how-do-i-create-and-read-a-value-from-cookie-with-javascript allows for all characters, and allows all options and their defaults.Gauffer
864e5 = 86400000 = 1000*60*60*24 represents the number of milliseconds in a 24 hour day.Leucoma
Pls, be aware that the above getCooki with reduce won't work properly for multiple cookies with the same name (possible for different paths, e.g. / and /faq). Chrome always provides cookies for the current path at the beginning of the document.cookie string. This reducer overwrites r value and returns the last found cookie value (so the value for / path instead of the current path value). Reduce also has poor performance (less important in this case), I made benchmarks here: measurethat.net/Benchmarks/Show/16012/2/…Member
Here is a fixed version of this function with = in value & duplicated name support: https://mcmap.net/q/55466/-how-do-i-create-and-read-a-value-from-cookie-with-javascript - but since it has poor performance I would consider other alternatives from that answer (there are comparisons).Member
H
45

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);
      }
   }
}
Hypoglycemia answered 28/1, 2011 at 6:59 Comment(1)
I'm marking this up primarily because you mentioned JQuery Cookies. I would recommend that. The code is very small and if you're using JQuery already, it is just the correct thing to use.Hidden
G
25

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);
Gauffer answered 9/2, 2018 at 13:21 Comment(12)
Would the downvoters kindly explain what's wrong with my method?Gauffer
1. Shorter, and IMO easier to maintain. 2. More complete (is the only answer to accept secure, any order of arguments, max-age). 3. More standard defaults (path etc defaults to the standard, unlike most answers here). 4. Best practice (according to MDN, the regex is the most reliable way to extract the values). 5. Futureprook (if more options are added to cookies, they will be maintained). 6. One object pollutes the code less than a bunch of functions. 7. Get, set and delete and easy to add more methods. 8. ES7 (yummy buzzwords).Gauffer
1) vscode is telling me I have to specify ES9 support for use of this line- "delete: (name, opts) => Cookie.set(name, '', {'max-age': -1, ...opts})". Is that what you found too? 2) to do a Cookie.get, can I just specify (name) versus (name, value). I may not know the value and am using the get to retrieve it.Hypoglossal
@Ric. 1. I don't get an error in VSCode. This has been valid since ES7, so not sure why you should have an issue. 2. When you are trying to retrieve the value, you don't know it yet. Do Cookie.get('name') w/o the value, and it will will return the value if it has been set. Hope that helps :)Gauffer
I'm completely with you, I thought it was ES7 too. Here is a link to the graphic of the error msg. Thx for help on point #2. i.imgur.com/uWNLXXE.pngHypoglossal
I've been implementing your cookie code above and have found a weird experience. If I only code the opts attribute "domain:", the last line "document.cookie = ..." works as expected, and writes a cookie. But for some reason when I add any other option the last same line appears to execute without bombing but the variable document.cookie always equals "". Any ideas here?Hypoglossal
There's no need to minify variables on Stack Overflow like c k v, str, opts, just use real variable names.Fike
@mikemaccana: When you solve math on a napkin, do you use number + 5 = 15 or integer * 7 = 14? i and int are perfectly well known and accepted variable names, as are n and num. {key: val} and {k: v} are as clear as {key: value}. str, arr, obj, are as verbose as they need to be, and opts is no less clear than then options. You can use an & instead of the word and even in a language that permits both. Verbosity is a virtue only when it adds clarity.Gauffer
@Gauffer In code (which isn’t mathematics), most people would do age + yearBorn = currentYear. Unlike mathematics, code sticks around and is read more than it is written and the overhead of having to find out that ‘c’ is cookie is unnecessary on those reading your code. This is why single character variable names are not considered good practice. You’re welcome to argue about this but I don’t think Stack Overflow is the place to do this.Fike
+9000. This is an excellent answer. I added one more item to my Cookie definition: MAX_AGE_SECONDS: 2147483647, This I use with set(..., ..., {"max-age": Cookie.MAX_AGE_SECONDS}) That crazy number comes from here: https://mcmap.net/q/56417/-set-a-cookie-to-never-expireCasia
It might also be nice to add (optional?) check in set() to throw exception if final cookie text exceeds 4,000 chars. Ref: #641438Casia
this code is mumbo jumbo unreadable, but maybe it was good by 2018 standardsStevie
C
19

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.

Cronin answered 29/5, 2014 at 23:54 Comment(7)
Please note that the cookie library provided on MDN is released under the GPL, not LGPL.Kauslick
What javascript file do I need to import? Couldn't find it :(Hippocampus
See the section under "Library" on this page: developer.mozilla.org/en-US/docs/Web/API/document/… - you can save it to a file and include it or paste it into an existing js file where you'd like to use it.Cronin
So no standalone javascript file? So it's a code snippet - not an actual library.Hippocampus
Great input! The "library" is a single .js file with ~80 lines; it's this file (on GitHub): github.com/madmurphy/cookies.js/blob/master/cookies.jsPeter
Top link is dead.Sculptress
Note that this is indeed Mozilla's GPL'ed code, or very close to it (and derivative GPL is GPL as well :) ). Mozilla has removed it from the main site, but they still archive it: developer.mozilla.org.cach3.com/en-US/docs/Web/API/Document/… — note how it retains the license notice, unlike the Gist provided. Use the Source, Luke, use the Source; don't trust to code on someone's web page who deliberately has erased a license... who knows what else they changed?Newsom
R
12

For those who need save objects like {foo: 'bar'}, I share my edited version of @KevinBurke's answer. I've added JSON.stringify and JSON.parse, that's all.

cookie = {

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

    get : function(name){
        var nameEQ = name + "=",
            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  JSON.parse(c.substring(nameEQ.length,c.length));
        }

        return null;
    }

}

So, now you can do things like this:

cookie.set('cookie_key', {foo: 'bar'}, 30);

cookie.get('cookie_key'); // {foo: 'bar'}

cookie.set('cookie_key', 'baz', 30);

cookie.get('cookie_key'); // 'baz'
Reddy answered 26/9, 2016 at 17:49 Comment(0)
X
10

I've used accepted answer of this thread many times already. It's great piece of code: Simple and usable. But I usually use babel and ES6 and modules, so if you are like me, here is code to copy for faster developing with ES6

Accepted answer rewritten as module with ES6:

export const createCookie = ({name, value, days}) => {
  let expires;
  if (days) {
    let date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = '; expires=' + date.toUTCString();
  } else {
    expires = '';
  }
  document.cookie = name + '=' + value + expires + '; path=/';
};

export const getCookie = ({name}) => {
  if (document.cookie.length > 0) {
    let c_start = document.cookie.indexOf(name + '=');
    if (c_start !== -1) {
      c_start = c_start + name.length + 1;
      let 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 '';
};

And after this you can simply import it as any module (path of course may vary):

import {createCookie, getCookie} from './../helpers/Cookie';
Xenolith answered 21/4, 2016 at 8:14 Comment(1)
FYI: toGMTString() is deprecated: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…. Use toUTCString() instead.Incunabula
M
7

Performance benchmark

Comparison of ES6 versions of some popular getCookie functions (with my improvements): https://www.measurethat.net/Benchmarks/Show/16012/5/getcookie-for-vs-forof-vs-indexof-vs-find-vs-reduce

TL;DR: for...of version seams to be fastest for real-life cookies data :)

Important: document.cookie can provide duplicated cookie names if there are cookies with the same name for path=/ and current page path (eg. path=/faq). But the cookie for the current path will always be the first in the string, so be aware of this when using the reduce() version from the other answer provided here (it returns the last found cookie instead of the first one).

Fixed reduce() version is further in my answer.

For..of version:

Fastest for the real-life benchmark data set (10 cookies with long values). But performance results are almost the same as with vanilla for loop and with Array.find(), so use which you like :)

function getCookieForOf(name) {
  const nameEQ = name + '=';
  for (const cookie of document.cookie.split('; ')) {
    if (cookie.indexOf(nameEQ) === 0) {
      const value = cookie.substring(nameEQ.length);
      return decodeURIComponent(value); // returns first found cookie
    }
  }
  return null;
}

IndexOf version

Incredibly fast in the artificial test set of 1000 cookies with short values (because it doesn't create an array with 1000 records). To be honest, I consider there could be a bug in the test code that makes this version so crazy fast (if you would find some, pls let me know). Anyway, it's rather not probable to have 1000 cookies in the real App ;)

It's slow for the real-world test data set with 10 long cookies.

function getCookieIndexOf(name) {
  const nameEQ = name + '=';
  const cookies = document.cookie;
  const cookieStart = cookies.indexOf(nameEQ);
  if (cookieStart !== -1) {
    const cookieValueStart = cookieStart + nameEQ.length;
    const cookieEnd = cookies.indexOf(';', cookieValueStart);
    const value = cookies.substring(
      cookieValueStart,
      cookieEnd !== -1 ? cookieEnd : undefined
    );
    return decodeURIComponent(value); // returns first found cookie
  }
  return null;
}

Array.find() version

function getCookieFind(name) {
  const nameEQ = name + '=';
  const foundCookie = document.cookie
    .split('; ')
    .find(c => c.indexOf(nameEQ) === 0); // returns first found cookie
  if (foundCookie) {
    return decodeURIComponent(foundCookie.substring(nameEQ.length));
  }
  return null;
}

Vanilla, old-school, for-loop version ;)

function getCookieFor(name) {
    const nameEQ = name + "=";
    const ca = cookies.split('; ');
    for(let i=0; i < ca.length; i++) {
        const c = ca[i];
        if (c.indexOf(nameEQ) === 0) {
          const value = c.substring(nameEQ.length);
          return decodeURIComponent(value); // returns first found cookie
        }
    }
    return null;
}

// ES5 version:
function getCookieFor(name) {
    var nameEQ = name + "=";
    var ca = cookies.split('; ');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        if (c.indexOf(nameEQ) === 0) {
          var value = c.substring(nameEQ.length);
          return decodeURIComponent(value); // returns first found cookie
        }
    }
    return null;
}

Array.reduce() version

My fixed version of this answer from @artnikpro - returns the first found cookie, so works better with duplicated cookie names for the current path (e.g. path=/faq) and path=/.

This version is the slowest one in all performance tests, so IMHO should be avoided.

function getCookieReduce(name) {
  return document.cookie.split('; ').reduce((r, v) => {
    const [n, ...val] = v.split('='); // cookie value can contain "="
    if(r) return r; // returns first found cookie
    return n === name ? decodeURIComponent(val.join('=')) : r; // returns last found cookie (overwrites)
  }, '');
}

You can run benchmarks by yourself here: https://www.measurethat.net/Benchmarks/Show/16012/5/getcookie-for-vs-forof-vs-indexof-vs-find-vs-reduce


setCookie() TypeScript function

Here is also my version of the function to set a cookie with encodeURIComponent, TypeScript, and SameSite option (which will be required by Firefox soon):

function setCookie(
  name: string,
  value: string = '',
  days: number | false = false, // session length if not provided
  path: string = '/', // provide an empty string '' to set for current path (managed by a browser)
  sameSite: 'none' | 'lax' | 'strict' = 'lax', // required by Firefox
  isSecure?: boolean
) {
  let expires = '';
  if (days) {
    const date = new Date(
      Date.now() + days * 24 * 60 * 60 * 1000
    ).toUTCString();
    expires = '; expires=' + date;
  }
  const secure = isSecure || sameSite === 'none' ? `; Secure` : '';
  const encodedValue = encodeURIComponent(value);
  document.cookie = `${name}=${encodedValue}${expires}; path=${path}; SameSite=${sameSite}${secure}`;
}

Google Chrome Cookie Storage API

Thanks to @oncode answer it's worth mentioning that the Google Chrome team has proposed some standardization (finally! It's really ridiculous that we still don't have any commonly accepted API for cookies) with asynchronous Cookie Storage API (available in Google Chrome starting from version 87): https://wicg.github.io/cookie-store/

Unfortunately, it's still unofficial and isn't even under W3C consideration nor ES proposal: github.com/tc39/proposals

Such a shame we still don't have any standard API for cookies...

Fortunately, we have cookie-store polyfill for other browsers as npm package (gitHub), which is only 1.7kB Gzipped ;)

Member answered 25/11, 2021 at 23:29 Comment(1)
Your answer needs more upvotes :) Extra kudos for suggesting benchmarks...Newsom
S
6

Here's a code to Get, Set and Delete Cookie in JavaScript.

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

function setCookie(name, value, expirydays) {
 var d = new Date();
 d.setTime(d.getTime() + (expirydays*24*60*60*1000));
 var expires = "expires="+ d.toUTCString();
 document.cookie = name + "=" + value + "; " + expires;
}

function deleteCookie(name){
  setCookie(name,"",-1);
}

Source: http://mycodingtricks.com/snippets/javascript/javascript-cookies/

Selfassertion answered 4/7, 2016 at 11:51 Comment(2)
Both links deadSculptress
Aye, it requires some searching on the Wayback Machine...Newsom
G
3

I've used js-cookie to success.

<script src="/path/to/js.cookie.js"></script>
<script>
  Cookies.set('foo', 'bar');
  Cookies.get('foo');
</script>
Gissing answered 13/9, 2017 at 21:9 Comment(1)
Definitely recommended. As of 2024, this project continues to be audited and validated all the time; new releases continue to be done regularly. And it's still less than 800 bytes (aye, bytes) gzipped.Newsom
P
3

Very short ES6 functions using template literals. Be aware that you need to encode/decode the values by yourself but it'll work out of the box for simplier purposes like storing version numbers.

const getCookie = (cookieName) => {
  return (document.cookie.match(`(^|;) *${cookieName}=([^;]*)`)||[])[2]
}
  
const setCookie = (cookieName, value, days=360, path='/') => {
  let expires = (new Date(Date.now()+ days*86400*1000)).toUTCString();
  document.cookie = `${cookieName}=${value};expires=${expires};path=${path};`
}

const deleteCookie = (cookieName) => {
  document.cookie = `${cookieName}=;expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/;`;
}  
Pomade answered 5/2, 2021 at 8:30 Comment(0)
I
2

I use this object. Values are encoded, so it's necessary to consider it when reading or writing from server side.

cookie = (function() {

/**
 * Sets a cookie value. seconds parameter is optional
 */
var set = function(name, value, seconds) {
    var expires = seconds ? '; expires=' + new Date(new Date().getTime() + seconds * 1000).toGMTString() : '';
    document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/';
};

var map = function() {
    var map = {};
    var kvs = document.cookie.split('; ');
    for (var i = 0; i < kvs.length; i++) {
        var kv = kvs[i].split('=');
        map[kv[0]] = decodeURIComponent(kv[1]);
    }
    return map;
};

var get = function(name) {
    return map()[name];
};

var remove = function(name) {
    set(name, '', -1);
};

return {
    set: set,
    get: get,
    remove: remove,
    map: map
};

})();
Intoxicant answered 4/11, 2015 at 10:0 Comment(0)
L
2

You can use my cookie ES module for get/set/remove cookie.

Usage:

In your head tag, include the following code:

<script src="https://raw.githack.com/anhr/commonNodeJS/master/cookieNodeJS/build/cookie.js"></script>

or

<script src="https://raw.githack.com/anhr/commonNodeJS/master/cookieNodeJS/build/cookie.min.js"></script>

Now you can use window.cookie for store user information in web pages.

cookie.isEnabled()

Is the cookie enabled in your web browser?

returns {boolean} true if cookie enabled.

Example

if ( cookie.isEnabled() )
    console.log('cookie is enabled on your browser');
else
    console.error('cookie is disabled on your browser');

cookie.set( name, value )

Set a cookie.

name: cookie name.
value: cookie value.

Example

cookie.set('age', 25);

cookie.get( name[, defaultValue] );

get a cookie.

name: cookie name.
defaultValue: cookie default value. Default is undefined.
returns cookie value or defaultValue if cookie was not found

Example

var age = cookie.get('age', 25);

cookie.remove( name );

Remove cookie.

name: cookie name.

Example

cookie.remove( 'age' );

Example of usage

Louie answered 6/6, 2019 at 3:52 Comment(1)
Nice, but is your library just for Node.js?Newsom
H
2

I use the following functions, which I have written by taking the best I have found from various sources and weeded out some bugs or discrepancies.

The function setCookie does not have advanced options, just the simple stuff, but the code is easy to understand, which is always a plus:

function setCookie(name, value, daysToLive = 3650) { // 10 years default
  let cookie = name + "=" + encodeURIComponent(value);
  if (typeof daysToLive === "number") {
    cookie += "; max-age=" + (daysToLive * 24 * 60 * 60);
    document.cookie = cookie + ";path=/";
  }
}
function getCookie(name) {
  let cookieArr = document.cookie.split(";");
  for (let i = 0; i < cookieArr.length; i++) {
    let cookiePair = cookieArr[i].split("=");
    if (name == cookiePair[0].trim()) {
      return decodeURIComponent(cookiePair[1].trim());
    }
  }
  return undefined;
}
function deleteCookie(name) {
  setCookie(name, '', -1);
}
Hortense answered 22/8, 2020 at 13:44 Comment(0)
R
2

The chrome team has proposed a new way of managing cookies asynchronous with the Cookie Storage API (available in Google Chrome starting from version 87): https://wicg.github.io/cookie-store/

Use it already today with a polyfill for the other browsers: https://github.com/mkay581/cookie-store

// load polyfill
import 'cookie-store';

// set a cookie
await cookieStore.set('name', 'value');
// get a cookie
const savedValue = await cookieStore.get('name');
Rotman answered 15/12, 2020 at 16:27 Comment(1)
Thx a lot for sharing this! Unfortunately, it's still unofficial and isn't even under W3C consideration nor ES proposal: github.com/tc39/proposals Such a shame we still don't have any standard API for cookies... it's ridiculous :P Fortunately cookie-store is only 1.7kB Gzipped ;) bundlephobia.com/package/[email protected]Member
S
2

For reading simple querystrings, this one-liner might work for you in recent versions of JavaScript:

let cookies = Object.fromEntries(document.cookie.split(';').map(i=>i.trim().split('=')));

And now you have a JavaScript Object with keys and values.

For creating, you can try this one:

let cookieObject = {foo: 'bar', ping: "pong"}
Object.entries(cookieObject).map((e)=>`${e[0]}=${e[1]}`).join(';')
Skiplane answered 23/7, 2021 at 22:52 Comment(3)
What do you recommend for writing cookies?Recovery
@Recovery i added one for writing, thanksSkiplane
Huh! One-liner FTW! Tough to read and work around in my head, but, sure, it seems to do the work! Well done :)Newsom
A
1

Through a interface similar to sessionStorage and localStorage:

const cookieStorage = {
  getItem: (key) {
    const cookies = document.cookie.split(';')
      .map(cookie => cookie.split('='))
      .reduce(
        (accumulation, [key, value]) => ({...accumulation, [key.trim()]: value}),
        {}
      )
    
    return cookies[key]
  },
  setItem: (key, value) {
    document.cookie = `${key}=${value}`
  },
}

Its usage cookieStorage.setItem('', '') and cookieStorage.getItem('').

Ancylostomiasis answered 10/2, 2021 at 18:0 Comment(1)
That's very clever of you. I like the rather well-standardised localStorage/sessionStorage facilities, so this looks good to me (I think). I wonder, couldn't this object be derived from the generic Storage object as well?Newsom
P
0

Simple way to read cookies in ES6.

function getCookies() {
    var cookies = {};
    for (let cookie of document.cookie.split('; ')) {
        let [name, value] = cookie.split("=");
        cookies[name] = decodeURIComponent(value);
    }
    console.dir(cookies);
}
Proximate answered 14/3, 2017 at 8:22 Comment(2)
cookies can contain '=' in a value string. This code won't work.Member
The question is also about creating cookies, not just reading themOptimism
A
-1

I have written simple cookieUtils, it has three functions for creating the cookie, reading the cookie and deleting the cookie.

var CookieUtils = {
    createCookie: function (name, value, expireTime) {
        expireTime = !!expireTime ? expireTime : (15 * 60 * 1000); // Default 15 min
        var date = new Date();
        date.setTime(date.getTime() + expireTime);
        var expires = "; expires=" + date.toGMTString();
        document.cookie = name + "=" + value + expires + "; path=/";
    },
    getCookie: function (name) {
        var value = "; " + document.cookie;
        var parts = value.split("; " + name + "=");
        if (parts.length == 2) {
            return parts.pop().split(";").shift();
        }
    },
    deleteCookie: function(name) {
        document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    }
};
Amorita answered 24/6, 2018 at 18:17 Comment(0)
H
-1

Here is the example from w3chools that was mentioned.

function setCookie(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 + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
Heliotropin answered 30/10, 2018 at 19:31 Comment(0)
U
-1

A simple read

var getCookie = function (name) {
    var valueStart = document.cookie.indexOf(name + "=") + name.length + 1;
    var valueEnd = document.cookie.indexOf(";", valueStart); 
    return document.cookie.slice(valueStart, valueEnd)
}
Unity answered 18/12, 2019 at 14:0 Comment(0)
C
-3

A cheeky and simple way of reading a cookie could be something like:

let username, id; 
eval(document.cookie); 
console.log(username + ", " + id); // John Doe, 123

This could be used if you know your cookie contains something like: username="John Doe"; id=123;. Note that a string would need quotes in the cookie. Not the recommended way probably, but works for testing/learning.

Cathe answered 26/10, 2018 at 17:29 Comment(1)
Eval is Evil. Don't.Newsom

© 2022 - 2024 — McMap. All rights reserved.