HTTP is a stateless protocol where the server does not remember the client which sent the request to it. To store this user specific login information, preferences, etc... data, and to enable the server to remember client, cookies were introduced. Cookie is a set of methods used to store data in client's browser. Typically they are small text files stored on local computer, which get exchanged between client and server in the HTTP header.

A Cookie has following pieces of information:

  • Name: A unique name identifying cookie. It is URL encoded.
  • Value: Value of the cookie. It is URL encoded.
  • Domain: Domain for which the cookie is valid. Many browser has restrictions on the number of cookies a domain can have.
  • Path: Specific path in the domain to which cookie has to be sent. “/” defines the current page and it is default value of path.
  • Expiration: A timestamp indicating when cookie should be expired. By default cookie is deleted once the browser is closed.
  • Secure Flag: When “secure” is included while creating cookie, the cookie information is sent to server only if there is SSL connection.

Each piece of above information is included as name-value pair in the Set-Cookie of the HTTP response sent from server as shown in the example below:

Example

Set-Cookie: name=AndroidUser; Expires=Sat, 10 Dec 2016 12:14:51 PM; domain=.android.com; Path=/; secure

In JavaScript the browser BOM object document.cookie is used to create, read, change and remove a cookie. 

Creating cookies

Cookies can be created like this:

Syntax

document.cookie = “name=AndroidUser; expires= Sat, 10 Dec 2016 12:14:51 UTC; path=/”;

Where expires and path are optional.

NOTE: The value of a cookie cannot contain commas, semicolons, white spaces …etc. Using encodeURIComponent() method ensures they have right values.

Reading cookies

Cookies can be read using document.cookie. However this returns the array of cookies containing all cookies. They have to be split to get individual values. 

Syntax

var allCookies = document.cookie;

The array is separated by ‘;’. Hence to get individual cookie, we split the array at ‘;’. And array is iterated till the cookie name is matched to require value.

Syntax for splitting Cookie array

cookieArray = allCookies.split(';');

Changing Cookie

A cookie's value can be changed using the same syntax as creating it. When a new cookie with same name is created, the old cookie is over-written.

Syntax

document.cookie = “name=iPhoneUser; expires= Sat, 10 Dec 2016 12:14:51 UTC; path=/”;

Removing Cookie

A cookie is deleted on closing the browser window by default. However by changing the expiry date to a date that has already passed, the cookie will be removed.

Example of working with JavaScript's cookies

 

›› go to examples ››