You can use JavaScript to get or set cookie values on the client.
Using the vanilla JavaScript API
In JavaScript,
document.cookie
Show archive.org snapshot
is an accessor to all cookies on the current site. It looks like a String, but its setter is actually more powerful.
When setting cookies this way, remember to set the path=/
option.
Reading cookies
A result may look like this:
hello=universe; foo=bar
This means that there are 2 cookies: "hello" with value "universe", and "foo" with value "bar".
It is actually just a String without any magic powers. In order to read a cookie's value, you need to parse the string:
document.cookie.match(/hello=([^;]+)/)[1]
// => "universe"
Set a cookie
Setting cookies works as simple as this:
document.cookie = "yes=please"
However, this will not overwrite any existing cookies. The document.cookie
setter will magically update your cookie list.
Reading again, we will see the cookie that we just stored, and any cookies that existed previously.
document.cookie
// => "hello=universe; foo=bar; yes=please"
That applies to all browsers.
Options
Cookie options like expiry or the path it is valid for can be set as part of the string:
document.cookie = "yes=please; expires=Sun, 1 May 2016 13:37:00 UTC; path=/"
Important: If you do not set a path
, the cookie will be valid for the current path only. You probably always want path=/
.
Remove a cookie
To remove a cookie, set its value to an empty string and use a past expiration date:
document.cookie = "yes=; expires=Thu, 01-Jan-70 00:00:01 UTC; path=/"
Using a library
If you are regularly working with cookies in JavaScript, you may want to use a library that simplifies this.
Cookies.js Show archive.org snapshot is small and works nicely. Here's a usage example:
Cookies.set('hello', 'universe')
// (sets a cookie)
Cookies.get('hello')
// => "universe"
Cookies.set('key', 'value', { expires: 600, secure: true })
// (sets a cookie that is flagged "Secure" and expires in 10 minutes)
Note that Cookies.js automatically sets path=/
by default which is nice.