Skip to main content

Saving and Using Cookies

This page describes how to save and use cookies, within a CSP-based web application.

A cookie is a name-value pair stored within the client browser. Every subsequent request from the client includes all of the previous cookie values.

Storing information within a cookie is useful for information that you want to remember past the end of a session. (To do this, you must set an expiration date as, by default, cookies end when the browser closes.) For example, you could remember a username in a cookie so that in a subsequent session they would not have to reenter this information.

Saving Cookies

To save a cookie, use the SetCookie() method of the %response object as in the following example:

 Do %response.SetCookie("UserName",name)

A cookie definition can include an expiration date and a path in this format:

 Do %response.SetCookie("NAME","VALUE",expireData,path)

A blank expireData field defines an in-memory cookie (available only during the current session). If, however, you specify a value for the expireData field, this becomes a permanent cookie that is removed at the time specified. The format for the expireData field is Wdy, DD-Mon-YYYY HH:MM:SS GMT, for example: Wednesday, 24-Mar-2024 18:12:00 GMT.

For details, see %CSP.ResponseOpens in a new tab in the class reference.

The SameSite Attribute

When creating a cookie, you can specify the SameSite argument, which determines how an application handles cookies in relation to third-party applications (aka cross-site requests). This argument overrides the default SameSite value specified by the web application.

If you specify that a cookie has a SameSite value of None, then you must use an HTTPS connection.

Accessing Cookies

Any cookies are available in the Cookies property of the %request object. This property is a multidimensional property, whose subscripts are the names of the cookies.

The %request object also provides methods for counting and iterating through the cookies. See GetCookie(), NextCookie(), and CountCookie() in %CSP.RequestOpens in a new tab. For example, the following simple page class displays all cookies and their values:

Class Sample.CookieDemo Extends %CSP.Page
{

ClassMethod OnPage() As %Status
{
   Set html="<!DOCTYPE html>"
           _"<html lang=""en"" dir=""ltr"">"
           _"<body>"
           _"<p>COOKIES:</p>" 
           _"<ul>"

   Set cookie=%request.NextCookie("")
   While cookie'="" { 
      For count=1:1:%request.CountCookie(cookie) { 
         Set html=html_"<li>"_cookie_" - "
                      _..EscapeHTML(%request.GetCookie(cookie,count))
                      _"</li>" 
       }
       Set cookie=%request.NextCookie(cookie)
   } 
   Set html=html_"</ul>"
                _"</body>"
                _"</html>"
 
   Write html
   Quit $$$OK
}

}
FeedbackOpens in a new tab