Cookies in widget code

Has anyone utilised cookies in the server side widget code?
We would like the browser to remember a users cstom filter options on a bespoke listing widget. The cookies can be set in the frontend.js when filters are applied, but would need to be retrieved in the server side main.js code.
I can’t find reference to this documentation. URL params can be accessed so the frontend.js could update the URL with pushState but this would rely on a page refresh for them to then be used.

Morning Jon,

Have you successfully set and get the cookie state?

If so from a server side perspective it is simply a matter of either loading the filters into the front end if the cookie is not empty and awaiting a user action to submit, or forcing the regular user action once the cookie filters have been applied. Your frontend.js will still need to apply the data in the same manner, the main.js (server side) will be oblivious to the source of the data.

Please feel free to let me know what you have tried, or if it is an existing widget you are modifying please let me know the specifics and I can see if we can help.

Hi Adam,
Thank you for your reply. Ideally we didn’t want the user to have to submit to re-filter the page, or call the server side code from the frontend.js as the listing is loaded server side on page load, so would have to refresh to then reapply the filters outlined in the cookie.
Is there a way to access the request[“cookies”] values server side in the main.js so they can be reapplied immediately, not by the client side having to make a new call to the server?

Hi Jon,

Apologies I missed your reply.
As I said you don’t have to wait, you can call the action to force the update once you have read the cookie. Calling the same action you would call if they had pressed the button. i.e. using this.trigger_action(‘search’,…) in frontend to call action_search: function(r){} in main.
You should be able to have this all happen in mounted.

/* frontend JS */
export default {
mounted:function(){
//Load Cookie and fire search.
},

Hi Adam. That makes sense.
I was loading the list in the get_template_data function, but by moving it into it’s own function I can trigger the action from the mounted frontend code - after first loading in the cookie values if there are any.
Thank you for your help.

1 Like