JavaScript Cookies: How to Create a Cookie with Javascript

You can create HTTP cookies on the devices of users that visit your website with the help of JavaScript. In this tutorial, I will demonstrate how to create cookies with JavaScript by giving some examples.

A cookie is a small piece of text file that is used for storing information associated to the web page it was created by. Whether you are building a website or a web application, you may need to make use of browser cookies to achieve certain things. For example, keeping a logged in user as logged in on the next visit, saving user preferences such as interface options or styles, keeping track of certain actions and events, starting and ending timers can all be considered among the potential uses of cookies.

Cookies are definitely not evil, as long as they are used responsibly, transparently and only for the purposes they are meant to. Unnecessary or incorrect use of cookies can be considered among bad web design practices, and it may cause usability problems on your website as well as security risks for your users, if not handled properly.

The European Union (EU) authorities even passed a legislation regarding online privacy, collection and use of personal information and use of web cookies by websites. You most probably have seen many websites so far with an EU cookie notice on them, informing you that the website uses certain cookies. As a side note, if your website will be accessible within any EU country, you should add a cookie notice on your website too, if it makes use of cookies, and explain in detail how they are used in your website's privacy policy.

You can create a cookie from the server side (the hosting server where your website is hosted) or from the client side (the web browser your visitor is using). In this tutorial, we will see how the client side cookies are created with JavaScript.

TIP: Also check the following tutorials that explain how to create a cookie and how to delete a cookie with PHP if you would like to learn about creating cookies from the server side.

Before we continue with creating cookies with JavaScript, you should also know the following about cookies so that you can use them properly.

- You can store only text -as information- in the cookie.
- The cookie that is created by Domain A will only be available to Domain A.
- You can store up to 4KB of data in a cookie.
- Cookies will disappear after their expiry time.
- Users can remove cookies one by one manually or by deleting their web browser history.
- The cookie content is visible to the web browser, hence to the user and anyone who may have access to that device. Therefore, do not store critical information (e.g. passwords) in cookies.

How to Set a Cookie with JavaScript

Setting a cookie with JavaScript is pretty easy. Using the cookie property of the document, here is how a cookie is set:

document.cookie = cookieContent

The content of the cookie is a sum of cookie attributes that you may use such as:

- name of the cookie and its value, this is the information that you will be storing in the cookie.
- path that the cookie is associated to. If not specified, the current document location is taken into account.
- domain that the cookie is associated to. Not required, useful if you want a certain subdomain to associate the cookie to.
- secure for cookies only to be transmitted via https or other secure protocols.
- expires for specifying the expiry date for the cookie.

The attributes are separated via semicolons (;). Here is a sample cookie creation with a name, path and expiry date:

document.cookie = "style=dark; path=/; expires=Sun, 25 Sep 2016 23:59:59 UTC";

The name of the above cookie is style, its value is dark and it expires on 25 Sep 2016 at 23:59:59 UTC time. Pay attention not to use double quotes (or single quotes if you embrace the cookie content with single quotes) or semicolons in the cookie value as it will break the code.

How to Update a Cookie with JavaScript

To update a cookie, or in other words to change the content or expiry time of a cookie, we use the same code above only with different values like the following:

document.cookie = "style=light; path=/; expires=Tue, 27 Sep 2016 23:59:59 UTC";

This will change the cookie from dark style to light style and extend its expiry time for two days.

How to Get a Cookie Value with JavaScript

Once a cookie is set, you can read its content via JavaScript. The following code returns all cookies associated to the current domain in a semicolon-separated string:

var cookies = document.cookie;

We will use the above code to get a specific cookie value (mycookie) like the following:

var cookieName = "mycookie=";
var cookies = document.cookie.split(";");

for (var i = 0; i < cookies.length; i++) {
  var s = cookies[i];
  while (s.charAt(0) == " ") s = s.substring(1, s.length);
  if (s.indexOf(cookieName) == 0) {
    var cookieValue = s.substring(cookieName.length, s.length);
  }
}

The above code will loop through all the cookies associated to the current domain and read the value of mycookie cookie.

How to Check If a Cookie Exists with JavaScript

One of the tasks you may need while working with cookies is to check whether a cookie exists (is set previously) or not. The following code will check if a cookie named as style exists or not.

if (document.cookie.indexOf("style") < 0) {
  // style cookie doesn't exist...
} else {
  // style cookie exists...
}

f t g+ in