JavaScript Cookies

last edited on: 19-Jan-2018; tagged: javascript,cookies

What is a Cookie?

A cookie is a small text file that we can store on user’s computer to store a small amount of data on the user's computer through the browser.

Why to use Cookies?

When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user. To solve this problem cookie were invented. We can store small information (recommendation is not to save sensitive information) using Cookies.

Create a Cookie using JavaScript

JavaScript can create, read/select, and delete cookies with the document.cookie property.

document.cookie = "username= Kate Lynch; expires=Sun, 31 Dec 2017 12:00:00 UTC; path=/";

In the above example we create cookie with three attribute.

  1. username => the name of the cookie. After the “username” we have set a value which is “Kate Lynch”.
  2. expires => An expiry date (in UTC time). By default, the cookie is deleted when the browser is closed.
  3. path => We can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page.


Read a Cookie with JavaScript

var cookies = document.cookie;
document.cookie will return all cookies in one string like: cookieName1=value; cookieName2=value; cookieName3=value;

Here we can use a custom function to find cookies with its name:

function getCookieByName(cookieName)
  var value = "; " + document.cookie;
  var parts = value.split("; " + cookieName + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();

Details about this function:

Considering that cookies are stored as below format:

"{name}={value}; {name}={value}; ..."

First we have added a "; " to the cookie name then we can first split by "; {name}=", and if this is found in a cookie string (i.e. we have two elements), we will end up with second element being a string that begins with our cookie value. Then we pull that out from an array with pop(), and repeat the same process, but now with ";" but this time pulling out the left string with shift() function to get the actual value.

Change/Edit/Modify a Cookie with JavaScript

Edit a cookie is same way as we create it

document.cookie = "username= Ara Gates; expires= Sun, 31 Dec 2017 12:00:00 UTC; path=/";

Delete a Cookie with JavaScript

We don't have to specify a cookie value when we need to delete a cookie. Just set the expires parameter to a passed date:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/"


JavaScript Form Validation

tagged: javascript,validation

PHP Cookies

tagged: php,cookies