JavaScript cookie attributes04:33

  • 0
Published on November 22, 2017

Link for all dot net and sql server video tutorial playlists

Link for slides, code samples and text version of the video

In this video we will discuss some of the optional cookie attribute values that can be specified when creating a cookie. This is continuation to Part 67, please watch Part 67 of JavaScript tutorial before proceeding.

Optional Cookie Attributes

The following code creates a cookie that expires as soon as the browser is closed
document.cookie = “color=red”;

expires and max-age attributes : If you want to create a persistent cookie, that is a cookie that is not deleted after the browser is closed either use expires or max-age attributes

document.cookie = “color=red;expires=Fri, 5 Aug 2016 01:00:00 UTC”;
document.cookie = “color=red;max-age=” + (60 * 60 * 24 * 30) + “;”// Creates a cookie that expires in 30 days

What is the difference between expires and max-age attributes
With expires attribute you set an expiry date. The expires attribute is obsolete. Very few modern browsers support this attribute. Internet Explorer is one of them.
With max-age attribute you specify the expiry time in seconds. Most modern browsers support this attribute except Internet Explorer.

If you want to create a persistent cookie that works in IE and all the other browsers then specify both expires and max-age attributes.

domain attribute : Specifies the doamin for which the cookie is valid. If you specify the doamin as then that cookie will be valid only for that sub-domain. It will not be valid for

If you want a cookie to be valid for all sub-domains of then specify So this cookie will be valid for

path attribute : By default cookies are valid only for web pages in the directory of the current web page that stored them, as well as its descendants.

Example : The following diagram shows the directory structure of a web application
// JavaScript cookie attributes.png

If a cookie is set by it will be valid for but not for

If you want to create a cookie that is valid across all your pages in your website, then set the path attribute to the root of your web directory, that is, “/”.

document.cookie = “color=red;max-age=” + (60 * 60 * 24 * 30) + “;path=/”;

secure attribute : secure attribute specifies that the cookie is secure and is only used over HTTPS protocol which ensures that the cookie is always encrypted when transmitting from client to server.

Enjoyed this video?
"No Thanks. Please Close This Box!"