Hi there. Today I wanna talk about a Cookie.
I know that very many developers are using a cookie but they are using set/get/delete
a cookie with some package like js-cookie
and they know about cookies a bit.
Set a Cookie
Start with what is cookies and why do you can want to use them.
Cookies are string
which are stored in the browser and this is a part of HTTP protocol. Your browser sends cookies to a web server that does the web like personal space.
You can be working with cookies in JavaScript. You can call document.cookie
in the console of a browser.
document.cookie
is not variable or something else. This works like setter/getter
. You can get cookies and write a cookie with this.
Write some cookie right now. You can do it in this browser's tab or any other tabs.
document.cookie = 'userName=Bill'
You see that cookie has a format like key=value
. In fact, the cookie has options but I am going to talk about this next.
A cookie's value can be any string so that you should use encodeURIComponent
. So you can use value with spaces and other symbols.
document.cookie = `${encodeURIComponent(key)}=${encodeURIComponent(value)}'
The Cookie options
Let's talk about a cookie's options.
You can write an option with the cookie using ;
separator like this
document.cookie = `${encodeURIComponent(key)}=${encodeURIComponent(value)}; keyOfOption1=value; keyOfOption2=value;'
path
The options about which pages of a website can get cookies. The path must be absolute. By defaults to the current setter path.
domain
The domain where your cookie will be available. If you set another domain name it is not working but you can set a cookie with a subdomain and do available a cookie for the subdomain of your website.
max-age
or expires
max-age
and expires
are synonyms.
max-age
is the time in seconds from this moment.
expires
is the date when your cookie will be deleted.
If neither max-age
nor expires
specified it will be expire at the browser has closed.
secure
Cookie with this option will be available only on the website by HTTPS protocol.
httpOnly
Cookie with these options sets web server. You cannot work with a cookie with this option. You cannot get/set/delete
the cookie.
samesite
The option has some values.
strict
The cookie with same site=strict
never sent in the request if you came from another domain.
lax
This soft variable of strict
value. If you use one of safe methods your cookies will be sent or if your request from head level (for example request from iframe will not be sent).
Delete cookie
You could guess that if you set max-age
as negative value of set expires
as a past date you will delete the cookie. That is true.
I hope that I help you know about cookies more in the post that you knew early.
Thank you for reading the post βΊοΈ
Useful resource https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
Top comments (0)