Sending Cookies to the Browser

The response object has a property called cookies that allows you to send cookies to the browser. To create a cookie, you create a new property in the cookies property. e.g.

response.cookies.myCookie = myValue;
response.cookies.myCookie.path = '/myWebApp';
var expireDate = new Date();
expireDate.setTime(expireDate.getTime() + 86400000);
response.cookies.myCookie.expires = expireDate.toGMTString();

This example will create a cookie called ‘myCookie’ with a value of ‘myValue’ that will be sent to the browser at the same time as the HTML page. The cookie will be returned to the server for all pages whose URL is under the path "/myWebApp" and the cookie will expire in 24 hours.

Cookie Properties

Property

Description

expires

This can be a Server-side script Date object or a string. This is used to set the time that the cookie expires.

If you want to use a string it has the format: ddd, dd-mmm-yyyy hh:mm:ss GMT

e.g. response.cookies.myCookie.expires = "Wed, 09-Nov-99 23:12:40 GMT";

Default action: If this is not set explicitly the cookie will last until the browser is closed.

path

This is a string that sets the URL path from which the cookie will be sent by the browser.

Default action: If this is not set explicitly it will be set to the path of the file that produced the cookie.

domain

This string can be used to allow the browser to send cookies to more than one machine. The only restriction on this is that it must contain at least two dots (e.g. .myserver.com).

IMPORTANT: The server issuing the cookie must be a member of the domain that it tries to set in the cookie. That is, a server called www.myserver.com cannot set a cookie for the domain www.yourserver.com.

Default action: If this is not set explicitly then it defaults to the full domain of the document creating the cookie.

secure

This is a boolean field used to indicate if the cookie should only be transmitted over a secure connection to the server.

Default action: If this is not set explicitly then it defaults to not secure.

Retrieving Cookies from the Browser

All cookies sent by the browser are placed in the cookies object. They are retrieved by using the name. For example ‘request.cookies.myCookie’ will return the value ‘myValue’.

If there is more than one cookie available with the same name then the value will be an array of cookie values. This array will be ordered on relevance of the domain name used to set the cookie. That means that the cookie set in domain ‘mydomain/first/page.html’ will be before the cookie set in domain ‘mydomain/first’.

Comment on this topic

Topic ID: 150111