Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 5.4Cookies in JavaScript

Part 5.4Cookies in JavaScript
Cookies

Cookies can be a very useful and powerful method of temporary storage and communication between a front end language and a backend language.

In a nutshell, a cookie is a piece of temporary storage on a client computer system or web browser. This information is then sent in a HTTP Header to the server on every subsequent request.

Cookies are persistent between either sessions or pages. With a session cookie, when the user leaves the session or closes the browser the session cookie is destroyed. With a cookie with an explicit expiration date, the cookie will remain on the client's computer system until the set time is reached.

One example of the use of a cookie is to create a more interactive basket for a user. Storing the basket in the cookie whilst the user adds items to the basket makes it quick and interactive for the user. Once the server receives the basket, the server can then move the basket to a server variable such as a session variable and then 'flush' the actual cookie on the client's computer. The cookie used here could simply be a session cookie. This also demonstrates an effective method of communication between the client side and server side languages.

Cookies are stored as plain text within a client's computer system.

Setting and retrieving cookies

When it comes to working with cookies, JavaScript does not have as 'clean' a solution as a language such as PHP or Java. The document object provides a cookie property which contains a single string that has all cookies:

JavaScript
//This will produce a string of all cookies in use on this website
alert(document.cookie);

Cookies should be in the format:

<name>=<value>;expires=<expiry>;path=<path>

Where anything within angled brackets (< >) is a variable placeholder that can be changed.

A cookie variable can only contain strings, integers and reals and booleans and cannot contain non-stringified objects or other types that do not fall in to these categories.

Feedback 👍
Comments are sent via email to me.