3

Getting and setting Cookies via JavaScript feels a little odd like this:

Set: document.cookie = "<key>=<value>[;expires=<utc_expires>[;path=<path>]]";

Get: parse document.cookie

I found this get and set function on W3C.org Cookies

Is there a more elegant/easy way to do this?

SirPilan
  • 4,649
  • 2
  • 13
  • 26
  • Possible duplicate of [Set cookie and get cookie with JavaScript](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript) – rnevius Nov 02 '18 at 05:12

2 Answers2

20

You can use some simple functions like setCookie() and getCookie().

You can set a cookie using the call:

setCookie('myName','value', 3);

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

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

Note: Source is from quirksmode. Please have a look at the docs if you want to know more about cookies.

  • 2
    So there is no more elegant way to do this? The getter and setter is essentially the same like to ones I've found on W3C.org – SirPilan Jul 12 '18 at 19:26
  • 1
    @Pilan: Also Mozilla provides a [simple framework for reading and writing cookies](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie/Simple_document.cookie_framework)- Once included on the page, you can set a cookie using: `docCookies.setItem(name, value);` This is probably the most elegant way how to achieve this. –  Jul 12 '18 at 19:28
  • 1
    Instead of the `while` loop you can use `document.cookie.split(';').map(c => c.trimLeft())` – David Ferreira Apr 09 '19 at 21:54
  • Also instead of `if (c.indexOf(nameEQ) == 0)` the following executes faster (doesn't search the whole string) and is more descriptive too: `if (c.startsWith(nameEQ))` – Chris Janicki Mar 08 '23 at 15:02
6

ES6 approach is:

const setCookie = (cookieKey, cookieValue, expirationDays) => {
  let expiryDate = '';

  if (expirationDays) {
    const date = new Date();

    date.setTime(`${date.getTime()}${(expirationDays || 30 * 24 * 60 * 60 * 1000)}`);

    expiryDate = `; expiryDate=" ${date.toUTCString()}`;
  }

  document.cookie = `${cookieKey}=${cookieValue || ''}${expiryDate}; path=/`;
}

const getCookie = (cookieKey) => {
  let cookieName = `${cookieKey}=`;

  let cookieArray = document.cookie.split(';');

  for (let cookie of cookieArray) {

    while (cookie.charAt(0) == ' ') {
          cookie = cookie.substring(1, cookie.length);
      }

    if (cookie.indexOf(cookieName) == 0) {
          return cookie.substring(cookieName.length, cookie.length);
      }
  }
}
ofcyln
  • 86
  • 2
  • 4