How to read cookies set by JavaScript in a Salesforce Apex Class

Sharing is Caring

I recently had a requirement to have JavaScript create a cookie and then read it in later by an Apex class. You would think you could simply create a cookie in JavaScript and then read it in Apex using the exact same name as the cookie, but that’s not exactly the case.

Cookies that need to be read by an Apex Class need to start with apex__ or they won’t be readable by Apex. One other thing to keep in mind is that if apex changes the cookies values they will be url encoded. For example, the @ symbol will have it’s value changed to the percentage sign and the hexadecimal version.

For this example, we’re assuming you want to set a cookie called “settings” to true as soon as the javascript loads. I’m using a standard pattern I’ve documented previously about 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 access the values in apex, we would probably have some sort of functions like the below 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 is Caring

Brian is a software architect and technology leader living in Niagara Falls with 13+ years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.