3

I'm trying to get and set cookies in an AuraEnabled method in conjunction with my lightning community. Right now I'm going off of the cookie class documentation and just trying to get anything to work from there.

When I use:

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

within an @AuraEnabled function it throws an error. Is this because the community isn't an apex page? Is there any documentation on using this class outside of apex pages? Thanks for any help you might be able to provide.

1

Lightning doesn't expose cookies to Apex Code, probably because of the minimalist API design. The only cookies sent are related to the current session Id. So, to get data into Apex Code, you need to pass it in as a parameter. If you want to store data on the client, use window.localStorage or window.sessionStorage instead. sessionStorage lasts as long as the browser is open, and localStorage lasts until explicitly cleared by the user or the developer.

These APIs also allow you to store 5MB of data per domain (2.5 million characters of Unicode data, since JavaScript always uses Unicode). Both of these interfaces are supported in Locker Service. For example, I wrote an example in this question that lets you use a sessionStorage-backed data provider to remember attribute values between page reloads. If you need to pass state back and forth, you'll need to arrange for that via parameters and return values:

public class State {
  @AuraEnabled public String someValue;
}
@AuraEnabled public static State someMethod(State input) {
  input.someValue = "Hello World";
  return input;
}
...

You should ideally only send as much data as you need to, though, so this design is usually of limited utility, but it's useful to know when you have a need for something like this.

2
  • So there's really no way for me to use cookies in a lightning community? I'm basically just trying to get the ID of an object and have that follow a guest or logged in user around to wherever they are in the community.
    – Eric Strom
    Mar 21 '18 at 1:15
  • you could create a component that stores the id and have other components fetch it with events on a per need basis
    – glls
    Mar 21 '18 at 4:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.