JavaScript Cookies

Cediba
Cediba
Nov 1 · 2 min read
Cookiemonster

Cookies are small text file, which JavaScript can write on the user’s computer. They hold a very small amount of data at a maximum capacity of 4KB. Cookies are used in different ways, such as in storing the pages visited on a site or a user’s login information. They are limited in that they can only store strings. Also they can’t store executable code. Have you ever saved your Facebook password so that you do not have to type it each and every time you try to login? If yes, then you are using cookies. Cookies are saved as key/value pairs.


There are four basic tasks we need to accomplish with cookies.

  • Create a cookie.
  • Read a cookie.
  • Update a cookie.
  • Delete a cookie.

How to create cookies

You can create cookies using document.cookie property like this.

document.cookie = "cookiename = cookievalue"

You can even add expiry date to your cookie so that the particular cookie will be removed from the computer on the specified date. If you do not set the expiry date, the cookie will be removed when the user closes the browser.

document.cookie = "Language = JavaScript; expires= Sat, 2 Nov 2019 12:00:00 UTC"

How to read cookies

The next function reads a cookie. If on the webiste already a cookie exists, the value is gonna be returned. If there is no cookie the return value will be empty.

allCookies = docuemnt.cookies;

This code will show all cookies as a list in a string sepearated by semicolon.

How to update cookies

For updating a cookie we just need to change the value.

document.cookie = "Language = Java; expires= Sat, 2 Nov 2019 12:00:00 UTC"

How to delete cookies

To delete a cookie is quite simple, you just need to set the value of the cookie to empty and set the value of expires parameter to a passed date.

document.cookie = "username=; expires=Thu, 01 Jan 2018 00:00:00 UTC;

Are cookies dangerous

Cookies can be sometimes dangerous. First of all the help to surf more easy, because they make already visited website more user-friendly. But on the other hand is always better to think twice why a website is asking for you to safe the cookies, there is usually a option where we can block the usage of cookies.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade