How To Retrieve Cookies Set By JavaScript In A Salesforce Apex Class

I recently encountered a requirement where JavaScript was used to create a cookie and then later read by an Apex class. One might assume that creating a cookie in JavaScript and then accessing it in Apex using the exact same name would work, but that’s not quite how it functions.

Cookies intended to be read by an Apex Class must begin with “apex__” or they won’t be accessible by Apex. Additionally, it’s important to note that if Apex modifies the cookie values, they will be URL encoded. For instance, the “@” symbol will have its value replaced with the percentage sign and its hexadecimal version.

In this example, let’s assume you want to set a cookie named “settings” to true as soon as the JavaScript loads. I’m following a standard pattern I’ve previously documented regarding using jQuery in Visualforce.

<script>
 
function j$(function() {
setCookie('apex__settings','true');
});
 
function setCookie(cookieName, value){
    var cookieString = cookieName + "=" + value;
    document.cookie = cookieString;
}
</script>

To retrieve the values in Apex, we would likely use functions similar to the following examples.

private string savedSettings = null;
  
    public PageReference OnLoad()
    {
        savedSettings = getCookie('settings');
    }
 
// Private method used to set the cookie value
    private void setCookieString(String cookieName, String value)
    {
        Cookie ck = ApexPages.currentPage().getCookies().get(cookieName);
         
        ck = new Cookie(cookieName, String.valueOf(value),null,-1,false);
         
        ApexPages.currentPage().setCookies(new Cookie[]{ck});
    }
     
    // Private method used to retrieve the cookie value
    private String getCookie(String cookieName)
    {
        Cookie ck = ApexPages.currentPage().getCookies().get(cookieName);
         
        return ck != null ? ck.getValue() : '';
    }   

Sharing demonstrates care.