WRITING COOKIES IN A SALESFORCE LIGHTNING COMMUNITY (FOR DUMMIES)

I was recently challenged by a customer to allow cross website awareness of a Community user. In this specific case, I needed to create a cookie that contained a user’s first name, username (email) and a session length.

I spent a few days trawling the forums and blogs to find a neat and clean way of creating a cookie within a Lightning component or via the Community header without much luck. In the end, I needed to turn to Visualforce.

Thankfully, the Salesforce developer website contains a fairly detailed outline of the APEX cookie class, which includes the following code snippet:

// A Visualforce controller class that creates a cookie

// used to keep track of how often a user displays a page

public class CookieController {
public CookieController() {
Cookie counter = ApexPages.currentPage().getCookies().get('counter');
// If this is the first time the user is accessing the page,

// create a new cookie with name 'counter', an initial value of '1',


// path 'null', maxAge '-1', and isSecure 'false'.

if (counter == null) {
counter = new Cookie('counter','1',null,-1,false);
} else {
// If this isn't the first time the user is accessing the page

// create a new cookie, incrementing the value of the original count by 1

Integer count = Integer.valueOf(counter.getValue());
counter = new Cookie('counter', String.valueOf(count+1),null,-1,false);
}
// Set the new cookie for the page
ApexPages.currentPage().setCookies(new Cookie[]{counter});
}
// This method is used by the Visualforce action {!count} to display the current

// value of the number of times a user had displayed a page.


// This value is stored in the cookie.

public String getCount() {
Cookie counter = ApexPages.currentPage().getCookies().get('counter');
if(counter == null) {
return '0';
}
return counter.getValue();
}
}

While I have a little bit of experience with coding/development, I’m by no means any good at it. I can read and understand the general structure, but I can’t write something from scratch. So, before I start changing any code, I need to understand what it actually does. Let’s skip the opening declarations (as we won’t be touching these anyway) and dip straight into the first proper line:

Cookie counter = ApexPages.currentPage().getCookies().get('counter');

Here, the code is declaring a new cookie variable called counter and filling it with the contents of an existing cookie – confusingly also called counter.

if (counter == null) {

Next, the code is checking to see if the new variable has any contents. If it’s empty, the following will run:

counter = new Cookie('counter','1',null,-1,false);

This line sets up the contents of the new cookie with the following settings:

  • The name is set to counter
  • The contents is a text value of 1
  • The path (folder) is blank. This would be handy if you need to restrict cookie access to specific areas of a website
  • An expiration time that forces deletion at the point the browser is closed
  • A flag that forces data transmission to only take place over a HTTPS (secure) connection set to false

See here for more on the make up of a cookie.

If an existing cookie is found, the following code is executed:

Integer count = Integer.valueOf(counter.getValue());
counter = new Cookie('counter', String.valueOf(count+1),null,-1,false);

This is very similar to the code above with the exception that we’re now taking the number contained in the existing cookie and 1 is being added to it (String.valueOf(count+1)). Now the cookie has been set up in the variable, it get’s written to the browser’s cache with the following:

ApexPages.currentPage().setCookies(new Cookie[]{counter});

The final section of code involves grabbing the cookie contents, which is just a minor variation of getValue that we’re already seen above, so let’s ignore it for now. With a better understanding of what the snippet is doing, I can now look at changing the code to meet my client’s needs, which are the following:

  • Record a user’s first name
  • Record a user’s username (for debug)
  • Record the session timeout (I’ll handle this via the session expiration of the cookie).

So first thing’s first, I don’t need to worry about reading an existing cookie, I just want to declare a new one and I’ll call it myCookie:

Cookie myCookie;

Next up, I need to gather the user’s first name and username. These will be stored in variables called myFirstName and myUsername:

string myFirstName
string myUserName
myFirstName = userinfo.getFirstName()
myUserName = userinfo.getUserName();

Then I need to package the cookie contents together, which will be called “Cookie4Chris”. The data within will look something like “Chris | chris@username.com” The second line will write the cookie to the browser’s cache.

myCookie = new Cookie('Cookie4Chris',myFirstName +' | '+ myUserName,null,-1,false);
ApexPages.currentPage().setCookies(new Cookie[]{myCookie});

So if we add the class declaration (and some retrieval code for debugging, which I haven’t changed from the original snippet), the final APEX should look like this:

// A Visualforce controller class that creates a cookie
public class CookieController {
public CookieController() {
Cookie myCookie;
string myFirstName;
string myUserName;
myFirstName = userinfo.getFirstName();
myUserName = userinfo.getUserName();
myCookie = new Cookie('Cookie4Chris',myFirstName +' | '+ myUserName,null,-1,false);
ApexPages.currentPage().setCookies(new Cookie[]{myCookie});
}
// This method is used by the Visualforce action {!count} to display the current
// value of the cookie for debug purposes.
public String getCount() {
Cookie myCookie = ApexPages.currentPage().getCookies().get('myCookie');
if(myCookie == null) {
return 'Empty';
}
return myCookie.getValue();
}
}

Now we have our APEX class, we need to build a VisualForce page that will run the code. We can again turn to the Salesforce’ developer page with the following snippet:

<apex:page controller="CookieController">
You have seen this page {!count} times
</apex:page>

Since we don’t want any output, we can ditch the middle line and add an extra bit that will stop the element from showing on the page.

<apex:page controller="CookieController" rendered="false">
</apex:page>

That’s the hard part over. We have a bit of code that will write a cookie and a basic VF page that will run it for us. Before we can place our new page on a Community site, we need to do a few little things:

  • Under “Visualforce Pages” in Setup, we need to find our created page and click edit. From there, we can tick the box next to “Available for Salesforce mobile apps and Lightning Pages”.
  • We also need to change the permissions of our target user base to include access to the Visualforce page and the APEX class.

Now we’re ready to add the page to our Community. Load the Builder as usual, add a Visualforce Page, select the cookie page from the list and set the size to 20 pixels (the smallest available).

Publish your Community page and you’re done!

Hope you found this helpful. If I’ve made any mistakes, please feel free to get in touch (blog@chrisemmett.co.uk) and let me know how to improve the method. Don’t be shy!