Sometimes, we may want to create and read a value from a cookie with JavaScript.
In this article, we’ll look at how to create and read a value from a cookie with JavaScript.
Creating a Cookie
We can create a cookie by setting the document.cookie
property with a string that has the key-value pair with the expires
key-value pair attached after it.
For instance, we can write:
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;
};
We create the setCookie
function that takes the name
, value
, days
, and path
parameters.
name
is the key of the cookie.
value
is the corresponding value of the key of the cookie.
days
is the number of days until it expires.
path
is the path for the cookie.
expires
has the date string of the expiry date.
toUTCString
returns the date string in UTC.
Then we set document.cookie
with the name
and value
with =
between it.
And we concatenate that with the expires
key-value pair after the semicolon.
And we add the path
after that.
Getting a Cookie
There’s no easy way to get a JavaScript cookie with native methods.
We’ve to extract the cookie ourselves given the key.
To do this, we write:
const getCookie = (name) => {
return document.cookie.split("; ").reduce((r, v) => {
const parts = v.split("=");
return parts[0] === name ? decodeURIComponent(parts[1]) : r;
}, "");
};
We split the document.cookie
string with ;
.
Then we call reduce
on the string array to split the parts by the =
sign with split
.
Then we check if the first entry of the array is the same as name
.
If it is, then we call decodeURIComponent
with parts[1]
to decode the value.
Otherwise, we return r
which has the remaining parts of the split document.cookie
string.
The 2nd argument of reduce
is an empty string which is the initial return value of reduce
.
Now when we call the 2 functions as follows:
setCookie("foo", "bar", 10);
console.log(getCookie("foo"));
We see that the console log should return 'bar'
.
Conclusion
We can get and set the document.cookies
string property to get and set cookies with JavaScript.