javascriptruby-on-railscookieswebpackerjs-cookie

Rails 6 with js-cookie library: cookie is set but not persistent


I've been trying to set up a very simple cookie just to see if the user has clicked the cookie consent banner. I'm trying to set the cookie with an expiration date in the future so the user doesn't get this message every visit. It works to set the cookie, but it only sets it for the current session. In IE11, it doesn't work at all.

My JavaScript for this is:

in custom.js:

import Cookies from 'js.cookie';

// Hide cookie disclaimer on agreement
$('.cookies-disclaimer button').on('click', function() {
  $('.cookies-disclaimer').hide();
  Cookies.set('cookies_consent', true, { expires: 365, sameSite: 'strict' });
});

// Check if the cookie disclaimer has already been accepted
function hideAlreadyAcceptedCookieDisclaimer() {
  var consent = Cookies.get('cookies_consent');
  if (!consent) {
    $('.cookies-disclaimer').show();
  }
}
hideAlreadyAcceptedCookieDisclaimer();

in my application.js I require the js file from node_modules:

require('js-cookie/src/js.cookie')
...
require('custom')

Solution

  • UPDATE:

    The problem seemed to be in the way I imported the file:

    1. I removed import Cookies from 'js.cookie'; from custom.js
    2. In my application.js I added the library with window.Cookies = require('js-cookie/src/js.cookie')

    All credits to this post for helping me out: https://discuss.rubyonrails.org/t/js-cookie/73808 and his original blogpost: https://translate.google.com/translate?hl=&sl=ru&tl=en&u=https%3A%2F%2Ftheglitchy.com%2Fn%2Fkak-ustanovit-js-cookie-na-rails-6-yarn-webpack