https://code.iamkate.com/javascript/using-cookies
Using cookies in JavaScript
Cookies are small items of data, each consisting of a name and a value, stored on behalf of a website by visitors’ web browsers. In JavaScript, cookies can be accessed through the document.cookie
object, but the interface provided by this object is very primitive. Cookies.js is a JavaScript object that allows cookies to be created, retrieved, and deleted through a simple and intuitive interface.
Download Cookies.js
Download one of the files below and either incorporate it into your code or serve it as a separate file.
File | Size | Description |
---|---|---|
Cookies.js | 661 bytes | Minified version |
Cookies.src.js | 3,957 bytes | Full version, with comments |
The code creates a global object, Cookies
, which has functions to create, retrieve, and delete cookies.
Creating cookies
Cookies can be created using the set
function, which takes the cookie name and value as parameters:
1 2 |
// create a cookie Cookies.set('theme', 'green'); |
---|---|
A cookie set in this way will be deleted when the visitor closes their web browser, will only be accessible within the current directory on the current domain name, and will be sent over both encrypted and unencrypted connections. These features can be controlled through an optional third parameter, which is an object with four possible properties.
The expiry
property allows the cookie can be given an expiry date. Cookies with an expiry date will persist between browsing sessions, and only be deleted when the expiry date is reached or the visitor instructs the browser to do so. The value of the property can be either a date on which the cookie will expire or a number of seconds after which the cookie should expire:
1 2 3 4 5 |
// create a cookie that expires after one hour Cookies.set('theme', 'green', {expiry : 3600}); // create a cookie that expires on 1st January 2030 Cookies.set('name', 'Kate Morley', {expiry : new Date(2030, 0, 1)}); |
---|---|
Every cookie is accessible only within a particular path, which defaults to the current directory — for example, a cookie set on a page at http://example.com/news/ would by default be accessible from http://example.com/news/archives/ but not from the home page of the site. The path
property allows an alternative path to be specified:
1 2 3 4 5 |
// create a cookie that is accessible anywhere on the site Cookies.set('theme', 'green', {path : '/'}); // create a cookie that is accessible only within the news directory Cookies.set('country', 'uk', {path : '/news/'}); |
---|---|
Every cookie is accessible only on a particular domain, which defaults to the current domain and its subdomains — for example, a cookie set on news.example.com would by default be accessible from archives.news.example.com but not from the main domain example.com. The domain
property allows an alternative domain to be specified:
1 2 |
// create a cookie that is accessible on all subdomains of example.com Cookies.set('theme', 'green', {domain : '.example.com'}); |
---|---|
Finally, the secure
property can be set to true to instruct the browser to send the cookie only over encrypted connections:
1 2 |
// create a cookie that is sent only over encrypted connections Cookies.set('theme', 'green', {secure : true}); |
---|---|
Retrieving cookies
The value of a cookie can be retrieved using the get
function, which takes the cookie name as a parameter:
1 2 |
// retrieve the value of the theme cookie var theme = Cookies.get('theme'); |
---|---|
If there is no cookie with the specified name, the value undefined
is returned. There may be more than one cookie with the same name if they were set for different paths or subdomains. In this case the get function returns the most specific cookie (the one set for the longest path). Passing true
as a second parameter to the get
function will cause it to return an array containing the values of all cookies with the specified name, in order of specificity:
1 2 |
// retrieve the values of any theme cookies var themes = Cookies.get('theme', true); |
---|---|
Deleting cookies
A cookie can be deleted using the clear
function, which takes the cookie name as a parameter:
1 2 |
// delete the theme cookie Cookies.clear('theme'); |
---|---|
If the cookie was set for a path or domain other than the current path and domain, these must be passed to the clear
function through its optional second parameter:
1 2 3 4 5 6 7 |
// delete the site-wide theme cookie Cookies.clear( 'theme', { path : '/', domain : '.example.com' }); |
---|---|
https://javascript.info/cookie
Cookies, document.cookie
Cookies are small strings of data that are stored directly in the browser. They are a part of the HTTP protocol, defined by the RFC 6265 specification.
Cookies are usually set by a web-server using the response Set-Cookie
HTTP-header. Then, the browser automatically adds them to (almost) every request to the same domain using the Cookie
HTTP-header.
One of the most widespread use cases is authentication:
- Upon sign in, the server uses the
Set-Cookie
HTTP-header in the response to set a cookie with a unique “session identifier”. - Next time when the request is sent to the same domain, the browser sends the cookie over the net using the
Cookie
HTTP-header. - So the server knows who made the request.
We can also access cookies from the browser, using document.cookie
property.
There are many tricky things about cookies and their options. In this chapter we’ll cover them in detail.
Reading from document.cookie
Does your browser store any cookies from this site? Let’s see:
// At javascript.info, we use Google Analytics for statistics,
// so there should be some cookies
alert( document.cookie ); // cookie1=value1; cookie2=value2;...
The value of document.cookie
consists of name=value
pairs, delimited by ;
. Each one is a separate cookie.
To find a particular cookie, we can split document.cookie
by ;
, and then find the right name. We can use either a regular expression or array functions to do that.
We leave it as an exercise for the reader. Also, at the end of the chapter you’ll find helper functions to manipulate cookies.
Writing to document.cookie
We can write to document.cookie
. But it’s not a data property, it’s an accessor (getter/setter). An assignment to it is treated specially.
A write operation to document.cookie
updates only cookies mentioned in it, but doesn’t touch other cookies.
For instance, this call sets a cookie with the name user
and value John
:
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
If you run it, then probably you’ll see multiple cookies. That’s because the document.cookie=
operation does not overwrite all cookies. It only sets the mentioned cookie user
.
Technically, name and value can have any characters. To keep the valid formatting, they should be escaped using a built-in encodeURIComponent
function:
// special characters (spaces), need encoding
let name = "my name";
let value = "John Smith"
// encodes the cookie as my%20name=John%20Smith
document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);
alert(document.cookie); // ...; my%20name=John%20Smith
Limitations
There are few limitations:
- The
name=value
pair, afterencodeURIComponent
, should not exceed 4KB. So we can’t store anything huge in a cookie. - The total number of cookies per domain is limited to around 20+, the exact limit depends on the browser.
Cookies have several options, many of them are important and should be set.
The options are listed after key=value
, delimited by ;
, like this:
document.cookie = "user=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"
path
path=/mypath
The url path prefix must be absolute. It makes the cookie accessible for pages under that path. By default, it’s the current path.
If a cookie is set with path=/admin
, it’s visible at pages /admin
and /admin/something
, but not at /home
or /adminpage
.
Usually, we should set path
to the root: path=/
to make the cookie accessible from all website pages.
domain
domain=site.com
A domain defines where the cookie is accessible. In practice though, there are limitations. We can’t set any domain.
By default, a cookie is accessible only at the domain that set it. So, if the cookie was set by site.com
, we won’t get it at other.com
.
…But what’s more tricky, we also won’t get the cookie at a subdomain forum.site.com
!
// at site.com
document.cookie = "user=John"
// at forum.site.com
alert(document.cookie); // no user
There’s no way to let a cookie be accessible from another 2nd-level domain, so other.com
will never receive a cookie set at site.com
.
It’s a safety restriction, to allow us to store sensitive data in cookies, that should be available only on one site.
…But if we’d like to allow subdomains like forum.site.com
to get a cookie, that’s possible. When setting a cookie at site.com
, we should explicitly set the domain
option to the root domain: domain=site.com
:
// at site.com
// make the cookie accessible on any subdomain *.site.com:
document.cookie = "user=John; domain=site.com"
// later
// at forum.site.com
alert(document.cookie); // has cookie user=John
For historical reasons, domain=.site.com
(a dot before site.com
) also works the same way, allowing access to the cookie from subdomains. That’s an old notation and should be used if we need to support very old browsers.
So, the domain
option allows to make a cookie accessible at subdomains.
expires, max-age
By default, if a cookie doesn’t have one of these options, it disappears when the browser is closed. Such cookies are called “session cookies”
To let cookies survive a browser close, we can set either the expires
or max-age
option.
expires=Tue, 19 Jan 2038 03:14:07 GMT
The cookie expiration date defines the time, when the browser will automatically delete it.
The date must be exactly in this format, in the GMT timezone. We can use date.toUTCString
to get it. For instance, we can set the cookie to expire in 1 day:
// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
If we set expires
to a date in the past, the cookie is deleted.
max-age=3600
Is an alternative to expires
and specifies the cookie’s expiration in seconds from the current moment.
If set to zero or a negative value, the cookie is deleted:
// cookie will die in +1 hour from now
document.cookie = "user=John; max-age=3600";
// delete cookie (let it expire right now)
document.cookie = "user=John; max-age=0";
secure
secure
The cookie should be transferred only over HTTPS.
By default, if we set a cookie at http://site.com
, then it also appears at https://site.com
and vice versa.
That is, cookies are domain-based, they do not distinguish between the protocols.
With this option, if a cookie is set by https://site.com
, then it doesn’t appear when the same site is accessed by HTTP, as http://site.com
. So if a cookie has sensitive content that should never be sent over unencrypted HTTP, the secure
flag is the right thing.
// assuming we're on https:// now
// set the cookie to be secure (only accessible over HTTPS)
document.cookie = "user=John; secure";
samesite
That’s another security attribute samesite
. It’s designed to protect from so-called XSRF (cross-site request forgery) attacks.
To understand how it works and when it’s useful, let’s take a look at XSRF attacks.
XSRF attack
Imagine, you are logged into the site bank.com
. That is: you have an authentication cookie from that site. Your browser sends it to bank.com
with every request, so that it recognizes you and performs all sensitive financial operations.
Now, while browsing the web in another window, you accidentally come to another site evil.com
. That site has JavaScript code that submits a form <form action="https://bank.com/pay">
to bank.com
with fields that initiate a transaction to the hacker’s account.
The browser sends cookies every time you visit the site bank.com
, even if the form was submitted from evil.com
. So the bank recognizes you and actually performs the payment.
That’s a so-called “Cross-Site Request Forgery” (in short, XSRF) attack.
Real banks are protected from it of course. All forms generated by bank.com
have a special field, a so-called “XSRF protection token”, that an evil page can’t generate or extract from a remote page. It can submit a form there, but can’t get the data back. The site bank.com
checks for such token in every form it receives.
Such a protection takes time to implement though. We need to ensure that every form has the required token field, and we must also check all requests.
Enter cookie samesite option
The cookie samesite
option provides another way to protect from such attacks, that (in theory) should not require “xsrf protection tokens”.
It has two possible values:
samesite=strict
(same assamesite
without value)
A cookie with samesite=strict
is never sent if the user comes from outside the same site.
In other words, whether a user follows a link from their mail or submits a form from evil.com
, or does any operation that originates from another domain, the cookie is not sent.
If authentication cookies have the samesite
option, then a XSRF attack has no chances to succeed, because a submission from evil.com
comes without cookies. So bank.com
will not recognize the user and will not proceed with the payment.
The protection is quite reliable. Only operations that come from bank.com
will send the samesite
cookie, e.g. a form submission from another page at bank.com
.
Although, there’s a small inconvenience.
When a user follows a legitimate link to bank.com
, like from their own notes, they’ll be surprised that bank.com
does not recognize them. Indeed, samesite=strict
cookies are not sent in that case.
We could work around that by using two cookies: one for “general recognition”, only for the purposes of saying: “Hello, John”, and the other one for data-changing operations with samesite=strict
. Then, a person coming from outside of the site will see a welcome, but payments must be initiated from the bank’s website, for the second cookie to be sent.
samesite=lax
A more relaxed approach that also protects from XSRF and doesn’t break the user experience.
Lax mode, just like strict
, forbids the browser to send cookies when coming from outside the site, but adds an exception.
A samesite=lax
cookie is sent if both of these conditions are true:
-
The HTTP method is “safe” (e.g. GET, but not POST).
The full list of safe HTTP methods is in the RFC7231 specification. Basically, these are the methods that should be used for reading, but not writing the data. They must not perform any data-changing operations. Following a link is always GET, the safe method.
-
The operation performs a top-level navigation (changes URL in the browser address bar).
That’s usually true, but if the navigation is performed in an
<iframe>
, then it’s not top-level. Also, JavaScript methods for network requests do not perform any navigation, hence they don’t fit.
So, what samesite=lax
does, is to basically allow the most common “go to URL” operation to have cookies. E.g. opening a website link from notes that satisfy these conditions.
But anything more complicated, like a network request from another site or a form submission, loses cookies.
If that’s fine for you, then adding samesite=lax
will probably not break the user experience and add protection.
Overall, samesite
is a great option.
There’s a drawback:
samesite
is ignored (not supported) by very old browsers, year 2017 or so.
So if we solely rely on samesite
to provide protection, then old browsers will be vulnerable.
But we surely can use samesite
together with other protection measures, like xsrf tokens, to add an additional layer of defence and then, in the future, when old browsers die out, we’ll probably be able to drop xsrf tokens.
httpOnly
This option has nothing to do with JavaScript, but we have to mention it for completeness.
The web-server uses the Set-Cookie
header to set a cookie. Also, it may set the httpOnly
option.
This option forbids any JavaScript access to the cookie. We can’t see such a cookie or manipulate it using document.cookie
.
That’s used as a precaution measure, to protect from certain attacks when a hacker injects his own JavaScript code into a page and waits for a user to visit that page. That shouldn’t be possible at all, hackers should not be able to inject their code into our site, but there may be bugs that let them do it.
Normally, if such a thing happens, and a user visits a web-page with hacker’s JavaScript code, then that code executes and gains access to document.cookie
with user cookies containing authentication information. That’s bad.
But if a cookie is httpOnly
, then document.cookie
doesn’t see it, so it is protected.
Appendix: Cookie functions
Here’s a small set of functions to work with cookies, more convenient than a manual modification of document.cookie
.
There exist many cookie libraries for that, so these are for demo purposes. Fully working though.
getCookie(name)
The shortest way to access a cookie is to use a regular expression.
The function getCookie(name)
returns the cookie with the given name
:
// returns the cookie with the given name,
// or undefined if not found
function getCookie(name) {
let matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
));
return matches ? decodeURIComponent(matches[1]) : undefined;
}
Here new RegExp
is generated dynamically, to match ; name=<value>
.
Please note that a cookie value is encoded, so getCookie
uses a built-in decodeURIComponent
function to decode it.
setCookie(name, value, options)
Sets the cookie’s name
to the given value
with path=/
by default (can be modified to add other defaults):
function setCookie(name, value, options = {}) {
options = {
path: '/',
// add other defaults here if necessary
...options
};
if (options.expires instanceof Date) {
options.expires = options.expires.toUTCString();
}
let updatedCookie = encodeURIComponent(name) + "=" + encodeURIComponent(value);
for (let optionKey in options) {
updatedCookie += "; " + optionKey;
let optionValue = options[optionKey];
if (optionValue !== true) {
updatedCookie += "=" + optionValue;
}
}
document.cookie = updatedCookie;
}
// Example of use:
setCookie('user', 'John', {secure: true, 'max-age': 3600});
deleteCookie(name)
To delete a cookie, we can call it with a negative expiration date:
function deleteCookie(name) {
setCookie(name, "", {
'max-age': -1
})
}
Updating or deleting must use same path and domain
Please note: when we update or delete a cookie, we should use exactly the same path and domain options as when we set it.
Together: cookie.js.
Appendix: Third-party cookies
A cookie is called “third-party” if it’s placed by a domain other than the page the user is visiting.
For instance:
- A page at
site.com
loads a banner from another site:<img src="https://ads.com/banner.png">
. - Along with the banner, the remote server at
ads.com
may set theSet-Cookie
header with a cookie likeid=1234
. Such a cookie originates from theads.com
domain, and will only be visible atads.com
: - Next time when
ads.com
is accessed, the remote server gets theid
cookie and recognizes the user: - What’s even more important is, when the user moves from
site.com
to another siteother.com
, which also has a banner, thenads.com
gets the cookie, as it belongs toads.com
, thus recognizing the visitor and tracking him as he moves between sites:
Third-party cookies are traditionally used for tracking and ads services, due to their nature. They are bound to the originating domain, so ads.com
can track the same user between different sites, if they all access it.
Naturally, some people don’t like being tracked, so browsers allow to disable such cookies.
Also, some modern browsers employ special policies for such cookies:
- Safari does not allow third-party cookies at all.
- Firefox comes with a “black list” of third-party domains where it blocks third-party cookies.
Please note:
If we load a script from a third-party domain, like <script src="https://google-analytics.com/analytics.js">
, and that script uses document.cookie
to set a cookie, then such cookie is not third-party.
If a script sets a cookie, then no matter where the script came from – the cookie belongs to the domain of the current webpage.
Appendix: GDPR
This topic is not related to JavaScript at all, just something to keep in mind when setting cookies.
There’s a legislation in Europe called GDPR, that enforces a set of rules for websites to respect the users’ privacy. One of these rules is to require an explicit permission for tracking cookies from the user.
Please note, that’s only about tracking/identifying/authorizing cookies.
So, if we set a cookie that just saves some information, but neither tracks nor identifies the user, then we are free to do it.
But if we are going to set a cookie with an authentication session or a tracking id, then a user must allow that.
Websites generally have two variants of following GDPR. You must have seen them both already in the web:
-
If a website wants to set tracking cookies only for authenticated users.
To do so, the registration form should have a checkbox like “accept the privacy policy” (that describes how cookies are used), the user must check it, and then the website is free to set auth cookies.
-
If a website wants to set tracking cookies for everyone.
To do so legally, a website shows a modal “splash screen” for newcomers, and requires them to agree to the cookies. Then the website can set them and let people see the content. That can be disturbing for new visitors though. No one likes to see such “must-click” modal splash screens instead of the content. But GDPR requires an explicit agreement.
GDPR is not only about cookies, it’s about other privacy-related issues too, but that’s too much beyond our scope.
Summary
document.cookie
provides access to cookies
- write operations modify only cookies mentioned in it.
- name/value must be encoded.
- one cookie must not exceed 4KB, 20+ cookies per site (depends on the browser).
Cookie options:
path=/
, by default current path, makes the cookie visible only under that path.domain=site.com
, by default a cookie is visible on the current domain only. If the domain is set explicitly, the cookie becomes visible on subdomains.expires
ormax-age
sets the cookie expiration time. Without them the cookie dies when the browser is closed.secure
makes the cookie HTTPS-only.samesite
forbids the browser to send the cookie with requests coming from outside the site. This helps to prevent XSRF attacks.
Additionally:
- Third-party cookies may be forbidden by the browser, e.g. Safari does that by default.
- When setting a tracking cookie for EU citizens, GDPR requires to ask for permission.
https://www.tabnine.com/academy/javascript/how-to-set-cookies-javascript/
JavaScript – How to Use Cookies with JavaScript
Cookies make it possible to store information about a web application’s user between requests.
After a web server sends a web page to a browser, the connection shuts down and all information held by the server is lost. This makes maintaining user state challenging, as we cannot refer to the server for values specific to the current user’s browser activity. Cookies overcome this obstacle by storing the required information on the user’s computer in the form of a name=value string.
Cookies are often used to store usernames, preferences, authentication tokens, and other similar items.
It is important to keep *security* in mind when storing sensitive information like authentication tokens. Cookies can be seen and modified by the user, potentially exposing sensitive information. For more about this issue see the section Set a path for a cookie below.
Set a cookie
Setting a cookie uses the following syntax:
document.cookie = ‘newCookie’
Let’s break this down into its components:
document.cookie is the command used to create a new cookie.
‘newCookie’
is a string that sets the cookie
value
. It has its own syntax to be aware of:
name=value
- For readability reasons name should imply what the cookie stores (e.g. username)
- value is simply the value.
Below is an example of setting a cookie using this syntax:
document.cookie = "username=Max Brown";
The above code will store a cookie named “username” with the value “Max Brown”.
Note: Cookies expire automatically based on an expiration date that can be set in code. If no expiration date is set, the cookie will be deleted as soon as the browser is closed. The next section covers setting an expiration date for your cookies.
Set an expiration date for a cookie
By default, cookies will be automatically deleted once the browser is closed. This prevents users from re-using the cookie values on subsequent visits to your page. You can override this by setting an expiration date for your cookie. This can be done easily by adding expires=expirationDate in UTC separated by semicolon from the name=value, as seen in the following example:
document.cookie = "username=Max Brown; expires=Wed, 05 Aug 2020 23:00:00 UTC";
The above example sets the “username” cookie to “Max Brown” as before, but it also adds an expiration date of Wednesday, August 5th, 2020, with an expiration time of 23:00:00 UTC. When this expiration time is reached, the cookie value will be deleted.
Note: UTC is a time standard (the coordinated universal time).
Set a path for a cookie
By default, cookies are associated with the page that sets them. This can lead to cookie values that are very easily traced by a curious user using developer tools. AS such, it is not advisable to store sensitive data on the root path for your application. Instead, you can provide a path where this data should be stored. The syntax for this is as follows:
document.cookie = "username=Max Brown; expires=Wed, 05 Aug 2020 23:00:00 UTC; path=/"
In the above example, we have set our “username” cookie with the value of “Max Brown”, and set its expiration to the same date as before. The difference is the path parameter, which modifies where the cookie is stored on the user’s machine. This is very useful when trying to store sensitive information, as it makes the information harder to find.
setCookie function
All of the above examples hard-code the cookie values, which will be of limited utility in most cases. Cookie values can also be set using a JavaScript function. Take the following code for example:
let username = 'Max Brown';
// Set a Cookie
function setCookie(cName, cValue, expDays) {
let date = new Date();
date.setTime(date.getTime() + (expDays * 24 * 60 * 60 * 1000));
const expires = "expires=" + date.toUTCString();
document.cookie = cName + "=" + cValue + "; " + expires + "; path=/";
}
// Apply setCookie
setCookie('username', username, 30);
This code defines a function, setCookie(). This function will create a cookie with the name “username”, value “Max Brown” with an expiration date of 30 days from the time it was created. Let’s explore this function line-by-line:
- In the first line of the function body, variable date is created and given the current date and time value in UTC as its initial value, This UTC timestamp will be formatted using the UTC timestamp format (e.g. Thu Aug 06 2020 12:41:34 GMT+0000 (UTC)). This value may be adjusted based on the user’s time zone.
- The next line of code converts the UTC timestamp above into a number (E.g. 1599308841783). This number is an integer known as the “epoch” time, or Unix time unit, and can be converted to a UTC timestamp easily. This allows us to easily manipulate the time using integer time differentials. The second part of this row uses this epoch time to calculate an expiration date for the cookie. It requires the number of milliseconds that you want your cookie expiration to take. The above code converts the parameter expDays (with a value of 30 as passed in above), and converts those requested days into an equivalent number of milliseconds. These milliseconds are then added to the Unix epoch timestamp, creating the target expiration date and time for our cookie.
- The third line declares a new variable expires, and gives it the value calculated for the expiration date in the previous line. This value is converted into a UTC string, which always shows GMT time as opposed to local time (e.g. Sat, 05 Sep 2020 12:38:16 GMT).
- The final line of the function sets the new cookie with all of the parameters populated:
username=Max Brown; expires=Sat, 05 Sep 2020 12:38:16 GMT; path=/
Update a cookie
To update a cookie, simply overwrite its value in the cookie object. You do this by setting a new cookie on the document with the same *Name*, but a different *Value*. The following code shows this in action:
username = 'Jen Brown';
setCookie('username', username, 30);
In the above code, we did not create a new cookie, as we already have a value in the cookie “username” of “Max Brown”. This call to setCookie() overwrites the value of the “username” cookie, changing it from “Max Brown” to “Jen Brown”.
Delete a cookie
To delete a cookie, you can simply provide an expiration date that occurred in the past. When the browser sees that the cookie has expired, it will delete the cookie automatically.
Fun fact: the formal Unix time count began on Thursday, January 1st 1970 at midnight GMT. This is known as the “Epoch” time. Timestamps in integers are similarly also known as “milliseconds since epoch”, or the number of milliseconds that have taken place since January 1st 1970.
To easily delete any cookie, simply set its expiration date as the epoch timestamp:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
This statement will delete a cookie named “username” if one exists.
Some browsers will not allow the deletion of a cookie if the path is not specified. Therefore, it is important to always specify the path when working with cookies.
Get cookies
Getting all cookies is very simple. Cookies are stored as a set of strings separated by semicolons. You can access this value by calling document.cookie as seen in the example below:
document.cookie = "username=Debra White; path=/";
document.cookie = "userId=wjgye264s; path=/";
let cookies = document.cookie;
console.log(cookies); // expected output: username=Debra White; userId=wjgye264s
The above code sets two cookies – username and userId, and returns the cookie values to the variable cookies as a single semicolon-delimited string. Note that the return value does not include the specified path.
Get a cookie
Retrieving the value of a single cookie requires a little bit of legwork.
First, we’ll write a function that can determine the value of a cookie when given the cookie’s name. Here is our sample code:
function getCookie(cName) {
const name = cName + "=";
const cDecoded = decodeURIComponent(document.cookie); //to be careful
const cArr = cDecoded .split('; ');
let res;
cArr.forEach(val => {
if (val.indexOf(name) === 0) res = val.substring(name.length);
})
return res;
}
Exploring function getCookie() by line
The function getCookie takes a cookie’s name as a parameter, then performs the following steps:
- The first line assigns the requested cookie name to a const variable name. It appends an equals sign to the end of the name. For example, passing in a cookie value ‘username’ will result in ‘username=’ being stored in the name variable.
- The next line retrieves all of the cookies using document.cookie, then applies decodeURIComponent() to the result. This function “cleans” the string from “encoding traces” that may have been included in the cookie content. You have likely seen these encoding traces before, they look similar to this: %20%24username%20.
- As explained in the previous section, document.cookie returns results as a string containing all cookie values separated by semicolons (;). Here I have used the split() method, asking it to split the string’s values apart when it encounters a semicolon followed by a blank space. The result will be an array of cookie strings.
- The following two lines define the return variable, res, and call the forEach() method on the array of cookies obtained in line 4 (cArr). The forEach() iterates through an array, executing a callback function once for each array element. In the above example, if the value stored in variable name appears at the beginning of the string (i.e. at index 0), the inner block assigns the content of the cookie (i.e. the value after the “=” sign) to the variable res. The value length is larger than index by one. This allows us to trim off both the full string name of the cookie, and the trailing equality sign by starting the trim at index = name.length. For trimming I used the substring() method, which produces a substring of the specified length from the original input string.
- If the forEach() method was not able to find the requested cookie, the value ‘undefined’ will be returned.
Keep in mind that in many cases, working with cookies will begin with fetching a cookie’s value, and then requesting information from the user if the requested cookie is not found.
Related Articles:
JavaScript – How to Use The Array forEach() Method
Modify Cookies – start off
https://stackoverflow.com/questions/2824021/create-a-cookie-if-and-only-if-it-doesnt-already-exist
if($.cookie('query') === null) {
$.cookie('query', '1', {expires:7, path:'/'});
}
Alternatively, you could write a wrapper function for this:
jQuery.lazyCookie = function() {
if(jQuery.cookie(arguments[0]) !== null) return;
jQuery.cookie.apply(this, arguments);
};
Then you'd only need to write this in your client code:
$.lazyCookie('query', '1', {expires:7, path:'/'});
From ASP.NET Cookies Overview:
You cannot directly modify a cookie. Instead, changing a cookie consists of creating a new cookie with new values and then sending the cookie to the browser to overwrite the old version on the client.
You can try this:
HttpCookie cookie = Request.Cookies["SurveyCookie"];
if (cookie == null)
{
// no cookie found, create it
cookie = new HttpCookie("SurveyCookie");
cookie.Values["surveyPage"] = "1";
cookie.Values["surveyId"] = "1";
cookie.Values["surveyTitle"] = "Definietly not an NSA Survey….";
cookie.Values["lastVisit"] = DateTime.UtcNow.ToString();
}
else
{
// update the cookie values
int newSurveyPage = int.Parse(cookie.Values["surveyPage"]) + 1;
cookie.Values["surveyPage"] = newSurveyPage.ToString();
}
// update the expiration timestamp
cookie.Expires = DateTime.UtcNow.AddDays(30);
// overwrite the cookie
Response.Cookies.Add(cookie);