Newer Version Available

This content describes an older version of this product. View Latest

Cookie Class

The Cookie class lets you access cookies for your Salesforce site using Apex.

Namespace

System

Usage

Use the setCookies method of the PageReference Class to attach cookies to a page.
  • Cookie names and values set in Apex are URL encoded, that is, characters such as @ are replaced with a percent sign and their hexadecimal representation.
  • The setCookies method adds the prefix “apex__” to the cookie names.
  • Setting a cookie's value to null sends a cookie with an empty string value instead of setting an expired attribute.
  • After you create a cookie, the properties of the cookie can't be changed.
  • Be careful when storing sensitive information in cookies. Pages are cached regardless of a cookie value. If you use a cookie value to generate dynamic content, you should disable page caching. For more information, see “Cache Salesforce Sites Pages” in the Salesforce online help.

Important

Consider the following limitations when using the Cookie class:
  • The Cookie class can only be accessed using Apex that is saved using the Salesforce API version 19 and above.
  • The maximum number of cookies that can be set per Lightning Platform domain depends on your browser. Newer browsers have higher limits than older ones.
  • Cookies must be less than 4K, including name and attributes.

For more information on sites, see “Salesforce Sites” in the Salesforce online help.

Example

The following example creates a class, CookieController, which is used with a Visualforce page (see markup below) to update a counter each time a user displays a page. The number of times a user goes to the page is stored in a cookie.

The following is the Visualforce page that uses the CookieController Apex controller above. The action {!count} calls the getCount method in the controller above.