This article is about HTTP cookies management in the client side (browser) via javascript.
Cookie are one way to store data in the browser.
document.cookie is a property of the browser document that returns the HTTP cookies that apply to the Document. If no cookies or cookies can't be applied to this resource, the empty string is returned.
With the Web API and Document cookie property
You can browse the cookies with the devtool
or an browser extension. Example: Chrome extension Edit this cookie
A cookie set with the HttpOnly flag, tells the browser that Javascript cannot access this cookie (ie the cookie should only be managed by the server and set in the browser request)
Set two cookies
document.cookie = "name=nico";
document.cookie = "favorite_color=blue";
console.log("All the cookies:");
console.log(document.cookie);
For the value of the google analytics cookie, see Google Analytics - Utma Cookie
console.log("All the cookies:");
console.log(document.cookie.split("; ").filter( (item) => item.trim().startsWith('_') ));
There is no function in the Javascript Web API to get a cookie by name.
We need to parse the value of document.cookie. This is a string of all cookies in a key pair format separated by a ;
cookie_key = "name";
document.cookie = cookie_key+"=nico";
regexp = new RegExp("(?:(?:^|.*;\\s*)"+cookie_key+"\\s*\\=\\s*([^;]*).*$)|^.*$");
var cookieValue = document.cookie.replace(regexp, "$1");
console.log("Regular expression : The value of the cookie with the name key is ("+cookieValue+")");
var cookieValue = document.cookie
.split(";")
.filter( (item) => item.trim().startsWith(cookie_key) )[0]
.split("=")[1];
console.log("Functional Programming: The value of the cookie with the name key is ("+cookieValue+")");
To delete a cookie, just set the expiration date in the past.
document.cookie = "key=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
Example:
import Cookies from "js-cookie";
Cookies.get('cookie-name');