Sometimes a theme needs to set a cookie, and a good way to do this, I find, is with js-cookie. Here’s how to use it with Sage 9:
Install
yarn add js-cookie
Import In Sage Scripts
Depend on where you need to use cookies, you’ll want to import js-cookie into a different scope. You can learn more about Sage’s javascript scoping in the Sage documentation. For this example, we’ll assume you need to use cookies everywhere on your site.
At the top of the appropriate javascript file, probably resources/scripts/routes/common.js, add:
import * as Cookies from "js-cookie";
Use Cookies!
In the appropriate javascript file (resources/scripts/routes/common.js in this example) add your cookie calls to the finalize() function:
export default {
init() {
...
},
finalize() {
...
// Set a cookie. See https://github.com/js-cookie/js-cookie for complete details
Cookies.set('name', 'value');
...
},
};
I recall having issues with cookies being set server-side not being available until a page-reload, but that might also be true with this method and I’ve just formed a habit.
So to answer your question, no, it’s just what I’ve always done.
Setting them server-side can definitely be more limiting: You have to set them before PHP has generated any output, or they just kind of fail silently. I like to set them that way when I’m doing, say, form processing, because then I can tie cookie generation more directly to processing, but I’ve had to set them in JS too, and it can be a bit frustrating. Thanks for the tip!