How to Read Cookies in Apex from a Salesforce Site

May 12, 2025


 

 

After completing this unit, you will be able to -

 

Introduction :

Salesforce Sites allow public users to access Visualforce pages without logging in. In some cases, you may want to use browser cookies to store or retrieve user-specific data like preferences or session info. Since Apex can’t directly read browser cookies, the solution is to use JavaScript to access the cookie and then pass it to Apex through a Visualforce page. This guide explains how to set up a Salesforce Site, use cookies in the browser, and send that data to Apex for use in your application.

What is a Salesforce Site, and What Are Cookies?

Salesforce Site is a feature that lets you expose your Visualforce pages and Apex logic to the public without requiring users to log in. It's useful for building custom web forms, landing pages, or public portals that interact with Salesforce data securely. Each site runs under a specific guest user profile, which must be configured with the right permissions to access Apex classes, Visualforce pages, and custom objects.

Cookies, on the other hand, are small pieces of data stored in the user's web browser. They help remember user preferences, session data, or other small bits of information across visits. Cookies are set and accessed using JavaScript on the client side and are often used for personalization or tracking purposes.

In Salesforce Sites, you can’t read cookies directly from Apex since Apex runs on the server. However, with the help of Visualforce and JavaScript, you can pass cookie data from the browser to the Apex controller when needed.

Set up the Apex Controller and Visualforce Page -

 

CookieController.cls

public with sharing class CookieController {
public String cookieValue { get; set; }

public PageReference getCookie() {
System.debug('--- Attempting to read cookie ---');
Map<String, Cookie> cookies = ApexPages.currentPage().getCookies();
System.debug('All cookies: ' + cookies);

if (cookies != null && cookies.containsKey('myCookieName')) {
Cookie myCookie = cookies.get('myCookieName');
this.cookieValue = myCookie.getValue();
System.debug('Cookie found: ' + this.cookieValue);
} else {
this.cookieValue = 'Cookie not found!';
System.debug('No cookie found with name "myCookieName"');
}
return null;
}
}

 

CookieSite.vfp

<apex:page controller="CookieController" showHeader="false" sidebar="false">
<h1>Cookie Test Page</h1>

<apex:form >
<apex:commandButton value="Get Cookie" action="{!getCookie}" rerender="output" />
</apex:form>

<apex:outputPanel id="output">
<p>Cookie Value From Apex: {!cookieValue}</p>
</apex:outputPanel>
<!-- <script>
console.log('Document domain:', document.domain);
</script>-->
</apex:page>

 

Creating a Salesforce Site and Configuring Access Permissions (Including Debug Logs)

Step 1: Create a Salesforce Site

  1. Go to Setup.
  2. In the Quick Find box, type "Sites" and click on Sites.
  3. If this is your first time, register your Force.com domain (e.g., yourname.force.com).
  4. After registering, click New under the Sites section.
  5. Fill in the required fields:
    • Site Label: CookieDemo
    • Site Name: Auto-generated
    • Site Contact: Your user
    • Default Web Address: Auto-filled
    • Active Site Home Page: Enter your Visualforce page name (e.g., CookieReaderPage)
  6. Click Save.

Step 2: Grant Access to the Visualforce Page and Apex Controller

  1. From the Sites list, click on your new site label (e.g., CookieDemo).
  2. Click Public Access Settings — this opens the Guest User Profile.
  3. In the profile:
    • Go to Enabled Visualforce Page Access → click Edit → move your VF page to the enabled list.
    • Go to Enabled Apex Class Access → click Edit → move your Apex controller (e.g., CookieControllerto the enabled list.
  4. Click Save after each step.

Step 3: Enable Debug Logs for the Guest User

To track what happens when the Site is accessed, enable debug logs for the guest user.

  1. Go to Setup → search for Debug Logs.
  2. Click New.
  3. For Traced Entity Name, click the lookup icon and search for your Site's Guest User:
    • Go to Sites → click your Site Label → click Public Access Settings → the user name at the top is the Guest User.
  4. In the Debug Level, select or create one called SFDC_DevConsole.
  5. Set Start Date and Expiration Date for the log.
  6. Click Save.

Now, every time the Site is accessed and code is run, a debug log will be generated for the guest user.

Set a Cookie in the Browser and Check the cookie in salesforce.

To test cookie reading in your Salesforce Site, you can manually set a cookie in your browser and then use your Visualforce page and Apex controller to retrieve it. Follow the steps below:

Step 1: Open the Site in a Custom Browser Window

  1. Copy the public Site URL (e.g., https://yourdomain.force.com/CookieReaderPage).
  2. Open this URL in your browser (preferably in incognito or a clean session).

Step 2: Manually Set the Cookie in the Browser

  1. Right-click on the page and select Inspect to open Developer Tools.
  2. Go to the Console tab.
  3. Paste and run the following JavaScript code:

document.cookie = "apex__myCookieName=myCookieValue;path=/;expires=3600;isSecure=false";

Note: The prefix apex__ is required for cookies to be accessible by Apex using ApexPages.currentPage().getCookies().

This creates a cookie named **apex__myCookieName** with the value **myCookieValue**.

Step 3: Trigger the Apex Method to Read the Cookie

  1. On your Visualforce page, click the "Get Cookie" or "Submit" button to invoke the Apex method (like getCookie()).
  2. This will allow Apex to attempt reading the cookie sent in the request.

Step 4: View the Debug Log in Salesforce

  1. In Setup, go to Debug Logs.
  2. If logging is enabled for your Site Guest User (as explained in the previous step), you’ll see a new log entry.
  3. Open the log and check our output are print or not.

Output:

 

Conclusion-

In summary, reading browser cookies in Apex through a Salesforce Site involves setting the cookie in the browser with the correct format, exposing a Visualforce page via a public site, and using Apex to retrieve the cookie. With proper access permissions and debug logs enabled, this setup helps pass client-side data to the server securely and effectively, allowing for personalized or session-based logic in public-facing Salesforce pages.