Getting or setting cookies is a straightforward operation that can be achieved by accessing the cookie property on the browser’s document object.
Let's say you find an amazing and informative recipe website to cook a fun meal for your guests but it’s in foreign language. Luckily you are able to change the language on the website using a dropdown.
A couple of days later you visit the same site again to make a dish for your mother, but now you see the website in your native language by default.
How'd that happen? The website remembers the language you selected on your last visit and stores it in the form of a cookie. Now it automatically selects your preferred language by reading that cookie.
Cookies are used to store data in the form of
name:value pairs on the client side. They let a website store user specific information on the browser for later use. The stored information could be
visitorLanguage and so on.
Another way to store the data on the client side is
A cookie can be set using the syntax below. But a library, like the one mentioned at the end, is highly recommended to make development easier for everyone.
While setting the cookie, you can set the expiration date for it as well. If you skip this, the cookies are erased when the browser is closed.
Keep in mind that a cookie set by a particular domain can only be read by that domain & its subdomains only.
The above cookie expires in 7 days.
In order to delete a cookie set the expiration date to something in the past.
If you find yourself playing with cookies a lot in your project, please use a library like this JS Cookie and save yourself a ton of time.