Roots Discourse

How To: js-cookie and Sage

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');

    ...

  },
};
9 Likes

Any particular reason you’d lean toward using JS to set your cookies rather than doing it server-side?

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!

@MWDelaney–Thank you for introducing this. Do you know how to use this to hide a bootstrap alert box for a day after it’s been dismissed?

What have you tried?

1 Like

I don’t really understand how it works which is why I asked :slight_smile:

I haven’t done that specifically, but some combination of the Bootstrap Alerts javascript events and the Cookie.set and Cookie.get methods from the js-cookie documentation will get it done for you.

2 Likes

Document says, import in main.js like this
import "slick-carousel/slick/slick.min";

Why you import in common.js ?