I want to save variable on server side (not in database). In Visualforce page we use Apex Controller and we can use session, can I use session in Lightning Web Components?

  • Hi Alexandr, in lightning aura or web component the state has to be maintained on client side; as all calls are static by design storing variable on server side is not possible. I am afraid that session may not be used for this type of caching. What are you trying to achieve in your use case?
    – Raul
    Feb 22 '20 at 20:51
  • Thank you for answer, I want to save custom object without store in database. If user fills special field - I insert it to database, it will one dml operation. Look! Maybe I can create session with public REST Api ?
    – Alexandr
    Feb 23 '20 at 6:54

So, you want to store data not in a table(Dirty object) on server side.

Had it been client-side, I would have recommended, cookies for <4KB, or Local Storage for up to 5MB storage.

But you want to store in server-side, so that its browser and device-independent as data is fetched from the server.

I would look into Session Platform Cache.

You can set and retrieve value in APEX and pass it on client side

// Add a value to the cache
DateTime dt = DateTime.parse('06/16/2015 11:46 AM');
Cache.Session.put('ns1.partition1.orderDate', dt);
if (Cache.Session.contains('ns1.partition1.orderDate')) {
    DateTime cachedDt = (DateTime)Cache.Session.get('ns1.partition1.orderDate');

Retrive Value back:

// Get a cached value
Object obj = Cache.Session.get('ns1.partition1.orderDate');
// Cast return value to a specific data type
DateTime dt2 = (DateTime)obj;

I would recommend using session cookies to have items in the browser.


There is a good answer on SFSE already: https://salesforce.stackexchange.com/a/270327/55914

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.