Coder Social home page Coder Social logo

nuxt-cookie-control's Introduction

Nuxt Cookie Control

ci status npm version npm downloads

nuxt-cookie-control

✅ Translated for: ar, az, bg, ca, cs, da, de, en, es, fi, fr, hr, hu, id, it, ja, ko, lt, nl, no, oc, pt, pl, ro, rs, ru, sk, sv, tr and uk

✅ Vue 3 support

⚠️ For Nuxt 2, please use nuxt-cookie-control < 3.0.0

🚩 API changes since continuing Dario Ferderber's work on gitlab.com/broj42/nuxt-cookie-control, make sure to read the README!

🚀 Getting Started

Stackblitz

Installation

npm i -D @dargmuesli/nuxt-cookie-control
yarn add -D @dargmuesli/nuxt-cookie-control
pnpm i -D @dargmuesli/nuxt-cookie-control

Configuration

// nuxt.config.js

modules: [
  '@dargmuesli/nuxt-cookie-control'
],
cookieControl: {
  // typed module options
}

// or

modules: [
  ['@dargmuesli/nuxt-cookie-control', {
    // untyped module options
  }]
]

Usage

<!-- app.vue -->

<template>
  <CookieControl locale="en" />
</template>

<script setup lang="ts">
const {
  cookiesEnabled,
  cookiesEnabledIds,
  isConsentGiven,
  isModalActive,
  moduleOptions,
} = useCookieControl()

// example: react to a cookie being accepted
watch(
  () => cookiesEnabledIds.value,
  (current, previous) => {
    if (
      !previous?.includes('google-analytics') &&
      current?.includes('google-analytics')
    ) {
      // cookie with id `google-analytics` got added
      window.location.reload() // placeholder for your custom change handler
    }
  },
  { deep: true },
)
</script>
//  plugins/analytics.client.ts

// example: initialization based on enabled cookies
const cookieControl = useCookieControl()

if (cookieControl.cookiesEnabledIds.value.includes('google-analytics')) {
  initGoogleAnalytics() // placeholder for your custom initialization
}

API

Module Options

// Position of cookie bar.
// 'top-left', 'top-right', 'top-full', 'bottom-left', 'bottom-right', 'bottom-full'
barPosition: 'bottom-full',

// Switch to toggle if clicking the overlay outside the configuration modal closes the modal.
closeModalOnClickOutside: true,

// Component colors.
// If you want to disable colors set colors property to false.
colors: {
  barBackground: '#000',
  barButtonBackground: '#fff',
  barButtonColor: '#000',
  barButtonHoverBackground: '#333',
  barButtonHoverColor: '#fff',
  barTextColor: '#fff',
  checkboxActiveBackground: '#000',
  checkboxActiveCircleBackground: '#fff',
  checkboxDisabledBackground: '#ddd',
  checkboxDisabledCircleBackground: '#fff',
  checkboxInactiveBackground: '#000',
  checkboxInactiveCircleBackground: '#fff',
  controlButtonBackground: '#fff',
  controlButtonHoverBackground: '#000',
  controlButtonIconColor: '#000',
  controlButtonIconHoverColor: '#fff',
  focusRingColor: '#808080',
  modalBackground: '#fff',
  modalButtonBackground: '#000',
  modalButtonColor: '#fff',
  modalButtonHoverBackground: '#333',
  modalButtonHoverColor: '#fff',
  modalOverlay: '#000',
  modalOverlayOpacity: 0.8,
  modalTextColor: '#000',
  modalUnsavedColor: '#fff',
},

// The cookies that are to be controlled.
// See detailed explanation further down below!
cookies: {
  necessary: [],
  optional: [],
}

// The milliseconds from now until expiry of the cookies that are being set by this module.
cookieExpiryOffsetMs: 1000 * 60 * 60 * 24 * 365, // one year

// Names for the cookies that are being set by this module.
cookieNameIsConsentGiven: 'ncc_c',
cookieNameCookiesEnabledIds: 'ncc_e',

// Options to pass to nuxt's useCookie
cookieOptions: {
  path: '/',
}

// Switch to toggle the "accept necessary" button.
isAcceptNecessaryButtonEnabled: true

// Switch to toggle the button that opens the configuration modal.
isControlButtonEnabled: true,

// Switch to toggle the concatenation of target cookie ids to the cookie description.
isCookieIdVisible: false,

// Switch to toggle the inclusion of this module's css.
// If css is set to false, you will still be able to access your color variables.
isCssEnabled: true,

// Switch to toggle the css variables ponyfill.
isCssPonyfillEnabled: false,

// Switch to toggle the separation of cookie name and description in the configuration modal by a dash.
isDashInDescriptionEnabled: true,

// Switch to toggle the blocking of iframes.
// This can be used to prevent iframes from adding additional cookies.
isIframeBlocked: false,

// Switch to toggle the modal being shown right away, requiring a user's decision.
isModalForced: false,

// The locales to include.
locales: ['en'],

// Translations to override.
localeTexts: {
  en: {
    save: 'Remember',
  }
}

Cookies

Every property that includes a { en: ... } value is a translatable property that could instead only specify a string ('...') or other locales as well ({ de: ..., uk: ... }).

{
  description: {
    en: 'This cookie stores preferences.'
  },
  id: 'p', // if unset, `getCookieId(cookie)` returns the cookie's slugified name instead, which e.g. is used to fill the state's `enabledCookieIds` list
  // use a short cookie id to save bandwidth!
  name: {
    en: 'Preferences' // you always have to specify a cookie name (in English)
  },
  links: {
    'https://example.com/privacy': 'Privacy Policy',
    'https://example.com/terms': 'Terms of Service',
  },
  src: 'https://example.com/preferences/js?id=<API-KEY>',
  targetCookieIds: ['xmpl_a', 'xmpl_b']
}

Component Slots

Bar

<CookieControl>
  <template #bar>
    <h2>Bar title</h2>
    <p>Bar description (you can use $cookies.text.barDescription)</p>
    <n-link>Go somewhere</n-link>
  </template>
</CookieControl>

Modal

<CookieControl>
  <template #modal>
    <h2>Modal title</h2>
    <p>Modal description</p>
  </template>
</CookieControl>

Cookie

<CookieControl>
  <template #cookie="{ cookie }">
    <h3 v-text="cookie.name" />
    <span v-html="cookie.description" />

    <div v-if="cookie.targetCookieIds">
      <b>Cookie ids: </b>
      <span v-text="cookie?.targetCookieIds?.join(', ')" />
    </div>
  </template>
</CookieControl>

Props

  • locale: ['en']
<CookieControl locale="de" />

nuxt-cookie-control's People

Contributors

abdullahhafizh avatar alexandrecanijo avatar alexnimoy avatar chz avatar danielroe avatar dargmuesli avatar darioferderber avatar den-kar avatar dependabot[bot] avatar devzom avatar gilles6 avatar hpawa avatar hslee2008 avatar huang-julien avatar kerneggertim avatar kukac7 avatar matt-rolley avatar maysomusician avatar milos5593 avatar misaon avatar onewaveadrian avatar onurdumangoz avatar patriciorivera avatar raducretu avatar renovate[bot] avatar roy-pon avatar sampovirmasalo avatar semantic-release-bot avatar tomfri avatar ventsislavborislavov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

nuxt-cookie-control's Issues

feat!: decline optional cookies, not all

Environment

  • Operating System: Linux
  • Node Version: v16.20.0
  • Nuxt Version: 3.7.0
  • CLI Version: 3.7.2
  • Nitro Version: 2.6.2
  • Package Manager: [email protected]
  • Builder: -
  • User Config: devtools, modules, cookieControl
  • Runtime Modules: @dargmuesli/[email protected]
  • Build Modules: -

Reproduction

https://stackblitz.com/edit/github-whwnbg?file=app.vue

Describe the bug

When clicking on the "Learn More and Customize" option in the cookie consent bar to open the modal, clicking "Decline All" closes the modal, and re-opens the consent bar.

The expected behavior is that all cookies should be declined, the modal closes, as well as the full consent bar.

If this is the intended behavior, would it be possible to allow that behavior to be configured through the nuxt.config? It appears that the code which would need to be changed is /src/runtime/components/CookieControl.vue line 270. isConsentGiven: false.

I would be happy to create a pull request for this issue.

Thanks!

Additional context

No response

Logs

No response

v3 error

I get the following error in console since v3:

using: nuxt3

Uncaught SyntaxError: The requested module '/_nuxt/node_modules/@dargmuesli/nuxt-cookie-control/dist/runtime/methods.mjs?v=f94e13d6' does not provide an export named 'getCookie' (at CookieControl.vue:167:1)

getName is not defined

Environment

Newest nuxt 2.X

Reproduction

Clicking acceptNecessary throws this error

Describe the bug

getName is not defined
at eval (nuxt-cookie-control.js:138:1)
at Array.map ()
at acceptNecessary (nuxt-cookie-control.js:138:1)
at invokeWithErrorHandling (vue.common.dev.js:3636:1)
at HTMLButtonElement.invoker (vue.common.dev.js:1483:1)
at original._wrapper (vue.common.dev.js:7931:1)

Additional context

necessary: [
  {
    //if multilanguage
    name: {
      en: 'Default Cookies',
      de: 'Standard-Cookies'
    },
    //else
    //name:  'Default Cookies',
    //if multilanguage
    description: {
      en:  'These cookies are required for the operation of the site.',
      de:  'Diese Cookies werden zum Betrieb der Seite benötigt.'
    },
    //else
    //description:  'Used for cookie control.',
    cookies: ['cookie_control_consent', 'cookie_control_enabled_cookies']
  }
],

Logs

export statement in CookieControl component's <script setup>

Environment

  • Operating System: Darwin
  • Node Version: v18.14.0
  • Nuxt Version: 3.3.1
  • Nitro Version: 2.3.3
  • Package Manager: [email protected]
  • Builder: vite
  • User Config: -
  • Runtime Modules: -
  • Build Modules: -

Reproduction

The error doesn't show in reproduction template, but it seems obvious and the solution is even in vue docs.

Describe the bug

There is an export statement inside script setup tag in CookieControl.vue which causes app to crash.
It's this block:

export interface Props {
  locale?: Locale
}

The export should be in a separate script tag (like vue documentation suggests), or in somewhere in types.

Additional context

No response

Logs

[plugin:vite:vue] [@vue/compiler-sfc] <script setup> cannot contain ES module exports. If you are using a previous version of <script setup>, please consult the updated RFC at https://github.com/vuejs/rfcs/pull/227.

/node_modules/@dargmuesli/nuxt-cookie-control/dist/runtime/components/CookieControl.vue
194|  import { getAllCookieIdsString, getCookieId, getCookieIds, removeCookie, resolveTranslatable } from '../methods'
195|  import setCssVariables from '#cookie-control/set-vars'
196|  import { useCookieControl, useCookie } from '#imports'
   |                                                         ^
197|  export 
   |  ^^^^^^^
198|  const props = withDefaults(defineProps<Props>(), {
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
199|    locale: 'en',
   |  ^^^^^^^^^^^^^^^
200|  })

docs: document migration and reactive state

How can i run a script if the cookie gets accepted. There should be an accepted function but it does not work.
Everything else works fine.

[
      "@dargmuesli/nuxt-cookie-control",
      {
        locales: ["de", "en"],
        cookies: {
          optional: [
            {
              id: "ga",
              name: {
                de: "Google Analytics ist ein von Google angebotener Webanalysedienst, der den Website-Verkehr verfolgt und meldet.",
                en: "Google Analytics",
              },
              src: "https://www.googletagmanager.com/gtag/js?id=G-*****",
              async: true,
              targetCookieIds: ["_ga", "*****", "_gid"],
              accepted: () => {
                console.log("TEST");
                window.dataLayer = window.dataLayer || [];
                function gtag() {
                  dataLayer.push(arguments);
                }
                gtag("js", new Date());

                gtag("config", "G-*****");
              },
            },
          ],
        },
      },
    ],
    ```

I want thai(th) languange

Describe the feature

I want Thai language Could you please add it to me? Thanks.

Additional information

  • Would you be willing to help implement this feature?

Final checks

The required node version (20) is incompatible with other nuxt packages

Environment

Nuxi 3.4.3

Nuxt project info:



Reproduction

There is no repro, as the problem occurs when installing after upgrading node to 20 to meet the new requirements added in dbf29b5 .

Describe the bug

Node 20 is set as a requirement for v5.8.0.
Most other Nuxt packages have their Node requirement set to versions below 20. This is also the case for core packages such as @nuxt/kit, @nuxt/schema and nitropack.

Thus after upgrading node to 20, I get the log messages below.

Additional context

No response

Logs

npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE   package: '@nuxt/[email protected]',
npm WARN EBADENGINE   required: { node: '^14.18.0 || ^16.10.0 || ^17.0.0 || ^18.0.0 || ^19.0.0' },
npm WARN EBADENGINE   current: { node: 'v20.1.0', npm: '9.6.4' }
npm WARN EBADENGINE }
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE   package: '@nuxt/[email protected]',
npm WARN EBADENGINE   required: { node: '^14.18.0 || ^16.10.0 || ^17.0.0 || ^18.0.0 || ^19.0.0' },
npm WARN EBADENGINE   current: { node: 'v20.1.0', npm: '9.6.4' }
npm WARN EBADENGINE }
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE   package: '@nuxt/[email protected]',
npm WARN EBADENGINE   required: { node: '^14.16.0 || ^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0' },
npm WARN EBADENGINE   current: { node: 'v20.1.0', npm: '9.6.4' }
npm WARN EBADENGINE }
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE   package: '[email protected]',
npm WARN EBADENGINE   required: { node: '^14.16.0 || ^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0' },
npm WARN EBADENGINE   current: { node: 'v20.1.0', npm: '9.6.4' }
npm WARN EBADENGINE }
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE   package: '[email protected]',
npm WARN EBADENGINE   required: { node: '^14.16.0 || ^16.10.0 || ^17.0.0 || ^18.0.0 || ^19.0.0' },
npm WARN EBADENGINE   current: { node: 'v20.1.0', npm: '9.6.4' }
npm WARN EBADENGINE }

Modal creates a lot of Functional cookie toggles

Environment



Reproduction

  • Implement the package on an existing website with loads of content

Describe the bug

A lot of functional cookies toggles are created.

There is not documentation on how this plugin works. Does it scan of existing cookies? Should they all be declared in the config? This would be unmaintainable since it already loads a mere 50, and with every exotic embed that number will increase. It cannot be true that they all have to be defined beforehand?

Or is this another type of bug?

Screenshot 2023-12-18 at 15 51 17

Additional context

cookieControl: {
	locales: ['nl'],
	closeModalOnClickOutside: true,
	cookieExpiryOffsetMs: 1000 * 60 * 60 * 24 * 365, // one year
	isIframeBlocked: true,
	isControlButtonEnabled: true,
	localeTexts: {
		nl: {
			bannerDescription: 'Lees hier meer of pas je cookievoorkeuren aan.',
			bannerTitle: 'Deze website maakt gebruik van cookies.',
			accept: 'Cookies toestaan',
			decline: 'Niet toestaan',
			acceptAll: 'Cookies toestaan',
			declineAll: 'Niet toestaan',
		},
	},
},

Logs

No response

Cookies not set

Environment

Reproduction

Nuxt.config.ts

['@dargmuesli/nuxt-cookie-control', {
colors: false,
isControlButtonEnabled: false,
cookies: {
necessary: [{
id: 'necessary',
name: 'Website and API',
description: 'Essential cookies for the website and API to work properly.',
targetCookieIds: ['cookie_control_consent', 'cookie_control_enabled_cookies', 'MuxData', 'next-auth'],
initialState: false
}],
optional: [{
id: 'google-analytics',
name: 'Google Analytics',
description: 'Helps us understand user behavior and optimize our services.',
targetCookieIds: ['_ga', 'gat'],
initialState: true,
}],
}
}]

Describe the bug

No cookies are set when I accept

Additional context

The Watch for isConsentGiven not triggered in CookieControl.vue (line 373) in library but I can see that it's triggered in my code when I create my own watch.

Logs

No response

implement "cookie" slot

Describe the feature

"cookie" slot is not yet implemented.

Additional information

  • Would you be willing to help implement this feature?

Final checks

fix: absolute paths error on windows

The issue when you add @dargmuesli/nuxt-cookie-control to the modules section of nuxt.config.ts

Cannot start nuxt: Only file and data URLs are supported by the default ESM loader. On Windows, absolute paths must be valid file:// URLs. Received protocol 'c:'

at new NodeError (node:internal/errors:371:5)
at defaultResolve (node:internal/modules/esm/resolve:1016:11)
at ESMLoader.resolve (node:internal/modules/esm/loader:422:30)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:222:40)
at ESMLoader.import (node:internal/modules/esm/loader:276:22)
at importModuleDynamically (node:internal/modules/esm/translators:111:35)
at importModuleDynamicallyCallback (node:internal/process/esm_loader:35:14)
at loadLocales (/C:/Users/akubasa/workspace/nuxt-app/node_modules/@dargmuesli/nuxt-cookie-control/dist/module.mjs:175:31)
at async setup (/C:/Users/akubasa/workspace/nuxt-app/node_modules/@dargmuesli/nuxt-cookie-control/dist/module.mjs:101:5)
at async normalizedModule (/C:/Users/akubasa/workspace/nuxt-app/node_modules/@nuxt/kit/dist/index.mjs:167:5)
at async installModule (/C:/Users/akubasa/workspace/nuxt-app/node_modules/@nuxt/kit/dist/index.mjs:416:3)
at async initNuxt (/C:/Users/akubasa/workspace/nuxt-app/node_modules/nuxt/dist/index.mjs:1825:7)
at async load (/C:/Users/akubasa/workspace/nuxt-app/node_modules/nuxi/dist/chunks/dev.mjs:6779:9)
at async Object.invoke (/C:/Users/akubasa/workspace/nuxt-app/node_modules/nuxi/dist/chunks/dev.mjs:6840:5)
at async _main (/C:/Users/akuba

Setting the `colors` option to `false` causes plugin not to run

Environment

------------------------------
- Operating System: `Linux`
- Node Version:     `v16.14.2`
- Nuxt Version:     `3.1.1`
- Nitro Version:    `2.0.0`
- Package Manager:  `[email protected]`
- Builder:          `vite`
- User Config:      `-`
- Runtime Modules:  `-`
- Build Modules:    `-`
------------------------------

Reproduction

https://stackblitz.com/edit/github-y7t61d?file=playground%2Fnuxt.config.ts

Describe the bug

The docs suggest you can define colors to false, to not use color variables. When doing this though, it causes the whole plugin (overlay) to just not load. No error messages either.

Additional context

No response

Logs

No response

GTM Script loaded in <script> but not running

Hello,

I am experiencing an issue with my GTM script that is unable to connect to Google Analytics.
After accepting cookies, the GTM script is included in the but is not being executed. Cookies are also not being set.

I would like to know if there is any way to fix this issue or if there are additional steps I should take to establish a connection to Google Analytics.

Thank you in advance for your help.

nuxt 3 nuxt.config.ts:


export default defineNuxtConfig({
  modules: [
    '@nuxtjs/i18n',
    '@nuxtjs/robots',
    [
      '@dargmuesli/nuxt-cookie-control',
      {
        barPosition: 'bottom-right',
        colors: {
          barBackground: '#26c281',
          modalButtonBackground: '#26c281',
          checkboxActiveBackground: '#26c281',
          controlButtonIconHoverColor: '#26c281',
          controlButtonHoverBackground: '#fff',
        },
        locales: ['de'],
        cookies: {
          necessary: [
            {
              name: {
                de: 'Standard Cookies',
                en: 'Default Cookies',
              },
              description: {
                de: 'Benötigen wir zur Cookie Kontrolle',
                en: 'Default Cookies',
              },
              cookies: [
                'cookie_control_consent',
                'cookie_control_enabled_cookies',
              ],
            },
          ],

          optional: [
            {
              name: {
                en: 'Google Tag Manager',
                de: 'Google Tag Manager',
              },
              description: {
                en: 'Google Analytics is a web analytics service offered by Google that tracks and reports website traffic.',
                de: 'Google Analytics ist ein von Google angebotener Webanalysedienst, der den Website-Verkehr verfolgt und berichtet.',
              },
              initialState: false,
              src: `https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXX`,
              async: true,
              accepted: () => {
                console.log('Google GTM ENABLED. ID=G-XXXXXXX');
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());

                gtag('config', 'G-XXXXXXXX');
              },
              declined: () => {
                console.log('Google GTM not allowed')
              },
            },
          ],
        },
      },
    ],
    '@funken-studio/sitemap-nuxt-3',
  ],
  i18n: {
    detectBrowserLanguage: {
      useCookie: true,
      cookieKey: 'i18n_redirected',
      redirectOn: 'root',
    },

    locales: [
      {
        code: 'de',
        file: 'de.json',
        name: 'German',
        iso: 'de-DE',
      },
    ],
    lazy: true,
    langDir: 'lang/',
    defaultLocale: 'de',
    vueI18n: {
      fallbackLocale: 'de',
    },
  },

  sitemap: {
    hostname: 'https://XXXXXXXX',
    gzip: true,
  },

  robots: {
    UserAgent: '*',
    Disallow: '',
  },

  css: ['~/assets/css/main.css'],
  postcss: {
    plugins: {
      tailwindcss: {},
      autoprefixer: {},
    },
  },
  plugins: [
    { src: './plugins/Vue3-particles.ts', ssr: false },
    { src: './plugins/Vue3Lottie.client.ts', ssr: false },
  ],
})




The method from the official nuxt-cookie-control readme is also not working:

optional: [
    {
      name:  'Google Analitycs',
      //if you don't set identifier, slugified name will be used
      identifier: 'ga',
      //if multilanguage
      description: {
        en:  'Google GTM is ...'
      },
      //else
      description:  'Google GTM is...',

      initialState: true,
      src:  'https://www.googletagmanager.com/gtag/js?id=<API-KEY>',
      async:  true,
      cookies: ['_ga', '_gat', '_gid'],
      accepted: () =>{
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
          'gtm.start': new Date().getTime(),
          event: 'gtm.js'
        });
      },
      declined: () =>{
      }
    }
  ]
}

Excessive stack depth comparing types 'NuxtModule<ModuleOptions>' and 'NuxtModule<ModuleOptions>'.

Environment

  • Operating System: Darwin
  • Node Version: v18.17.1
  • Nuxt Version: 3.7.3
  • CLI Version: 3.8.4
  • Nitro Version: 2.6.3
  • Package Manager: [email protected]
  • Builder: -
  • User Config: devtools, modules
  • Runtime Modules: @dargmuesli/[email protected]
  • Build Modules: -

Reproduction

Create a new Nuxt 3 project with nuxi and add @dargmuesli/nuxt-cookie-control to the modules.

Describe the bug

Installing the module in a project with Nuxt 3 v 3.7.3 causes the following TS errors:

  • Excessive stack depth comparing types 'NuxtModule<ModuleOptions>' and 'NuxtModule<ModuleOptions>'. ts(2321)
  • Type instantiation is excessively deep and possibly infinite. ts(2589)

Looking at the yarn.lock file, it seems the module causes a conflict with the dependency @nuxt/kit, where two versions are installed: 3.7.1 and 3.7.3

Additional context

No response

Logs

No response

Rollup failed to resolve import on Windows 11 during build

Environment

- Operating System: `Windows_NT`
- Node Version:     `v16.19.1`
- Nuxt Version:     `3.3.1`
- Nitro Version:    `2.3.1`
- Package Manager:  `[email protected]`
- Builder:          `vite`
- User Config:      `modules`, `cookieControl`
- Runtime Modules:  `@dargmuesli/[email protected]`
- Build Modules:    `-`

Reproduction

Using Windows create new bare project:

npx nuxi init newproject
npm install

Add package with npm (or yarn):

npm i -D @dargmuesli/nuxt-cookie-control

Follow the steps in README to add the module

  • added configuration on nuxt.config.js
  • added component to root app.vue

Build the project using
npm run build

Describe the bug

Build fails with the following error:

 ERROR  [vite]: Rollup failed to resolve import "C:UsersusernameProjects                                                                                                     
ewproject
ode_modules@dargmuesli
untimecomposables" from "C:/Users/username/Projects/newproject/app.vue?vue&type=script&setup=true&lang.ts".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
`build.rollupOptions.external`

  ewproject
  ode_modules@dargmuesli
untimecomposables" from "C:/Users/username/Projects/newproject/app.vue?vue&type=script&setup=true&lang.ts".
  This is most likely unintended because it can break your application at runtime.
  If you do want to externalize this module explicitly add it to
  `build.rollupOptions.external`
  at onRollupWarning (/C:/Users/username/Projects/newproject/node_modules/vite/dist/node/chunks/dep-ca21228b.js:44792:19)
  at onwarn (/C:/Users/username/Projects/newproject/node_modules/vite/dist/node/chunks/dep-ca21228b.js:44562:13)
  at Object.onwarn (/C:/Users/username/Projects/newproject/node_modules/rollup/dist/es/shared/node-entry.js:25103:13)
  at ModuleLoader.handleInvalidResolvedId (/C:/Users/username/Projects/newproject/node_modules/rollup/dist/es/shared/node-entry.js:23778:26)
  at /C:/Users/username/Projects/newproject/node_modules/rollup/dist/es/shared/node-entry.js:23738:26
  at processTicksAndRejections (node:internal/process/task_queues:96:5)

For some reason it seems that Windows path got truncated (backslahes removed)

Additional context

No response

Logs

No response

Consent is now being requested on a per path basis, which wasn't the case in v5.9.2

Environment

Nuxi 3.5.3

Nuxt project info:



Reproduction

I am unfortunately unable to produce a repro on stackblitz.
It stalls at "Booting WebContainer".

Describe the bug

If cookies are accepted in a page other than the homepage, the cookies from nuxt-cookie-control are set with a path matching the current route's path, thus if we visit a different path, consent is requested again.

For example, if the site is at example.com, and you first visit example.com/about and give consent there, then the cookies would have their path set to /about instead of /. Thus if you then visit example.com/credits, you will be asked for consent again (you might need to refresh the page as this will not happen if the page is displayed via Ajax).

This was not the case in version 5.9.2, I thus had to revert to it in order to work around this issue.

Additional context

No response

Logs

No response

fix(vite): support iframe blocking

Environment

Reproduction

nuxt.config.ts settings this option isIframeBlocked: true

Describe the bug

Setting isIframeBlocked: true does not block iFrames (e.g. Vimeo Player)

Additional context

No response

Logs

No response

The automated release is failing 🚨

🚨 The automated release from the beta branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the beta branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


Good luck with your project ✨

Your semantic-release bot 📦🚀

feat: don't include the css vars ponyfill in build when disabled

Describe the feature

Hey there,
I am using v3.4.0 and setting the css vars ponyfill integration to false:

export default defineNuxtConfig({
	modules: [
		'@dargmuesli/nuxt-cookie-control',
	],

	// @dargmuesli/nuxt-cookie-control
	cookieControl: {
		isCssPolyfillEnabled: false,
	},
})

Though in my build logs, it's getting integrated into the client when nuxt generate:

// ...
.nuxt/dist/client/_nuxt/css-vars-ponyfill.esm.495bc596.js   31.91 kB │ gzip: 10.18 kB
// ...

I can also see it in the build analyzer, taking a large chunk of my app 😄
Bildschirm­foto 2023-02-06 um 06 25 33

Additional information

  • Would you be willing to help implement this feature?

Final checks

Uncaught (in promise) Error: Could not get translation for locale pt.

Environment

yarn add -D @dargmuesli/nuxt-cookie-control

Reproduction

<CookieControl locale="pt"/>

Describe the bug

       Uncaught (in promise) Error: Could not get translation for locale pt.
    at Proxy.resolveTranslatable (methods.mjs?v=f59448ea:19:11)
    at CookieControl.vue:399:54
    at renderList (chunk-X4BLWDOR.js?v=f59448ea:3907:16)
    at CookieControl.vue:391:35
    at renderList (chunk-X4BLWDOR.js?v=f59448ea:3925:18)
    at CookieControl.vue:372:21
    at Proxy.renderFnWithContext (chunk-X4BLWDOR.js?v=f59448ea:2140:13)
    at Proxy.<anonymous> (chunk-X4BLWDOR.js?v=f59448ea:3115:79)
    at renderComponentRoot (chunk-X4BLWDOR.js?v=f59448ea:2172:39)
    at ReactiveEffect.componentUpdateFn [as fn] (chunk-X4BLWDOR.js?v=f59448ea:6173:26```

### Additional context

_No response_

### Logs

_No response_

feat: wcag compliance

Describe the feature

Make all components wcag complicant, e.g. by adding labels to icons.

Additional information

  • Would you be willing to help implement this feature?

Final checks

docs(readme): explain watcher for reactive variables

Describe the feature

Is there a way that when the user accepts the cookies, we can have an event listener like

<CookieControl locale="en" @accepted="cookiesAccepted" />

Thank you!

Additional information

  • Would you be willing to help implement this feature?

Final checks

No difference in status after clicking 'accept' or 'decline' buttons

Environment

browser

Reproduction

watch(
() => cookieControl.isConsentGiven.value,
(current, _previous) => {
console.log(cookie isConsentGiven current=${JSON.stringify(current,null,4)})
console.log(cookie isConsentGiven previous=${JSON.stringify(_previous,null,4)})
},
{ deep: true }
)

logs the same:

cookie isConsentGiven current=true
cookie isConsentGiven previous=false

for both buttons 'accept' and 'decline'

Describe the bug

In both cases isConsentGiven changes from false to true:

const accept = () => {
setCookies({
isConsentGiven: true,
cookiesOptionalEnabled: moduleOptions.cookies.optional,
})
}

const decline = () => {
setCookies({
isConsentGiven: true,
cookiesOptionalEnabled: moduleOptions.cookies.necessary,
})
}

so no way to determine which choice is done.

Seems that setting
isConsentGiven: true,
when decline() in not logically correct.

The changes
undefined --> true when accept()
undefined --> false when decline()
would look logically better.

Additional context

If initial status of isConsentGiven is undefined
then it becomes possible to watch a change in

const declineAll = () => {
setCookies({
isConsentGiven: false,
cookiesOptionalEnabled: [],
})
}

which now is impossible.

Logs

No response

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two Factor Authentication for your account, set its level to "Authorization only" in your account settings. semantic-release cannot publish with the default "
Authorization and writes" level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot 📦🚀

fix(i18n): locales overriding not working

Environment



Reproduction

inside the nuxt.config.ts

cookieControl: {
        localeTexts: {
            it: {
                bannerTitle: "Cookie",
                bannerDescription: "Questo sito utilizza i cookie per migliorare la tua esperienza di navigazione.",
                accept: "Accetta",
                decline: "Declina",
                manageCookies: "Gestisci i cookie",
                save: "Salva",
                cookiesNecessary: "Cookie necessari",
                cookiesFunctional: "Cookie funzionali",
                cookiesOptional: "Cookie opzionali",
                acceptAll: "Accetta tutti",
                declineAll: "Declina tutti",
                close: "Chiudi",
                here: "qui",
                iframeBlocked: "Per visualizzare questo contenuto è necessario accettare i cookie funzionali.",
                settingsUnsaved: "Le impostazioni non sono state salvate.",
            },
            en: {
                bannerTitle: "Cookies",
                bannerDescription: "This website uses cookies to improve your experience.",
                accept: "Accept",
                decline: "Decline",
                manageCookies: "Manage cookies",
                save: "Save",
                cookiesNecessary: "Necessary cookies",
                cookiesFunctional: "Functional cookies",
                cookiesOptional: "Optional cookies",
                acceptAll: "Accept all",
                declineAll: "Decline all",
                close: "Close",
                here: "here",
                iframeBlocked: "To view this content you need to accept functional cookies.",
                settingsUnsaved: "The settings have not been saved.",
            },
            de: {
                bannerTitle: "Cookies",
                bannerDescription: "Diese Website verwendet Cookies, um Ihre Erfahrung zu verbessern.",
                accept: "Akzeptieren",
                decline: "Ablehnen",
                manageCookies: "Cookies verwalten",
                save: "Speichern",
                cookiesNecessary: "Notwendige Cookies",
                cookiesFunctional: "Funktionale Cookies",
                cookiesOptional: "Optionale Cookies",
                acceptAll: "Alle akzeptieren",
                declineAll: "Alle ablehnen",
                close: "Schließen",
                here: "hier",
                iframeBlocked: "Um diesen Inhalt anzuzeigen, müssen Sie funktionale Cookies akzeptieren.",
                settingsUnsaved: "Die Einstellungen wurden nicht gespeichert.",
            }
        },
        colors: {
            barTextColor: "#fff",
            barBackground: "#12957b",
            barButtonColor: "#fff",
            barButtonBackground: "#206569",
            barButtonHoverColor: "#fff",
            barButtonHoverBackground: "#2e495e",
            modalButtonBackground: "#206569",
            modalButtonHoverColor: "#fff",
            controlButtonBackground: "#12957b",
            controlButtonHoverBackground: "#2e495e",
            controlButtonIconHoverColor: "#fff",
            controlButtonIconColor: "#fff",
            modalButtonHoverBackground: "#2e495e",
            checkboxActiveBackground: "#2e495e",
            checkboxInactiveBackground: "#ede1e1",
            checkboxActiveCircleBackground: "#00c58e",
            checkboxInactiveCircleBackground: "#f44336",
            checkboxDisabledBackground: "#ddd",
            checkboxDisabledCircleBackground: "#fff"
        },
        cookies: {
            necessary: [
                {
                    description: {
                        it: 'Questo nostro cookie memorizza le impostazioni fatte in questo dialogo.',
                        de: 'Dieser Cookie speichert die Einstellungen, die Sie in diesem Dialog getroffen haben.',
                        en: 'This cookie stores the settings you have made in this dialog.',
                    },
                    name: {
                        it: 'Cookie di preferenze',
                        de: 'Cookie-Präferenzen',
                        en: 'Cookie Preferences',
                    },
                    targetCookieIds: [
                        'cookie_control_is_consent_given',
                        'cookie_control_cookies_enabled_ids',
                    ],
                }
            ],
            optional: [
                {
                    description: {
                        it: 'I cookie di Google Analytics aiutano a capire come viene utilizzato questo sito web. Questi cookie memorizzano informazioni, come il numero di visitatori del sito, il tempo trascorso sul sito e le pagine visitate, in modo anonimo e aggregato.',
                        de: 'Die Cookies vom Drittanbieter Google ermöglichen die Analyse von Nutzerverhalten. Diese Analyse hilft uns unsere Dienste zu verbessern, indem wir verstehen, wie diese Webseite genutzt wird.',
                        en: 'The third-party cookies by Google enable the analysis of user behavior. This analysis helps us to improve our services by understanding how this website is used.',
                    },
                    id: 'google-analytics',
                    name: 'Google Analytics',
                    targetCookieIds: ['_ga', '_ga_xxxxxxxxx'],
                },
                {
                    description: {
                        it: 'I cookie di Clarity Analytics aiutano a capire come viene utilizzato questo sito web. Questi cookie memorizzano informazioni, come il numero di visitatori del sito, il tempo trascorso sul sito e le pagine visitate, in modo anonimo e aggregato.',
                        de: 'Die Cookies vom Drittanbieter Clarity Analytics ermöglichen die Analyse von Nutzerverhalten. Diese Analyse hilft uns unsere Dienste zu verbessern, indem wir verstehen, wie diese Webseite genutzt wird.',
                        en: 'The third-party cookies by Clarity Analytics enable the analysis of user behavior. This analysis helps us to improve our services by understanding how this website is used.',
                    },
                    id: 'clarity-analytics',
                    name: 'Clarity Analytics',
                    targetCookieIds: ['CLID', '_clck', '_clsk'],
                },
                {
                    description: {
                        it: 'I cookie di Crisp Chat servono a gestire la chat in tempo reale con il nostro team di supporto.',
                        de: 'Die Cookies vom Drittanbieter Crisp Chat dienen zur Verwaltung des Live-Chats mit unserem Support-Team.',
                        en: 'The third-party cookies by Crisp Chat are used to manage the live chat with our support team.',
                    },
                    id: 'crisp-chat',
                    name: 'Crisp Chat',
                    targetCookieIds: ['CLID', '_clck', '_clsk'],
                },

            ],
        },
        // locales:[]
        locales: ['en', 'de', "it"],
    },

Describe the bug

If i try to write the locale texts for "it" and "de" it works correctly when i remove "it" and "de" from the locales array.
But about "en" locale i cannot do anything because the plugin put it by itself and overwrites my localeTexts, and as an update I'm not able to overwrite only part of the texts it could be interesting to overwrite partially the prewrited ones.

fix(component): cookie toggles do not show the correct state when `isIframeBlocked` is enabled

Environment

It was tested in the playground of the repo.

Reproduction

It was tested in the playground of the repo.

Describe the bug

When Setting the toggle for optional cookies to disable and reloading the page, the toggle still shows active.
What I also recognized is that the values inside the cookie: 'ncc_c' are not using any separators. (intentional ?)

Video:
https://github.com/dargmuesli/nuxt-cookie-control/assets/60323626/3f799f5a-59b7-497d-9a7c-3b132b443126

Additional context

No response

Logs

No response

Types fail since [email protected]

Environment

Reproduction

I can provide it if needed, but it should pretty easy to reproduce, as it is sufficient to update to 3.9.0

Describe the bug

Look at the title

Additional context

No response

Logs

No response

Support package usage with Vite

Describe the feature

Hey, I'm trying to use this package with nuxt3 but it feels like it doesn't work whenever I'm trying to do this

// nuxt.config.js

modules: [
  '@dargmuesli/nuxt-cookie-control'
],
cookieControl: {
  // typed module options
}

the typing is not recognized in this case

but in this case, it's recognized
// nuxt.config.js

modules: [
  ['@dargmuesli/nuxt-cookie-control', {
    // untyped module options
  }]
]

and in default.vue (my default layout)

<template>
  <CookieControl locale="en" />
</template>

<script setup lang="ts">
const {
  cookiesEnabled,
  cookiesEnabledIds,
  isConsentGiven,
  isModalActive,
  moduleOptions,
} = useCookieControl()
</script>

the component and the composable is not recognized maybe I'm missing some import ?

Here's my package.json

{
  "private": true,
  "scripts": {
    "build": "nuxt build",
    "dev": "nuxt dev",
    "generate": "nuxt generate",
    "preview": "nuxt preview"
  },
  "devDependencies": {
    "@dargmuesli/nuxt-cookie-control": "^6.4.5",
    "@nuxt/content": "^2.6.0",
    "@nuxt/image-edge": "^1.0.0-rc.1-28143901.afe4120",
    "@nuxtjs/tailwindcss": "^6.7.2",
    "@tailwindcss/typography": "^0.5.9",
    "@types/rss": "^0.0.30",
    "nuxt-simple-robots": "^3.0.2",
    "nuxt-simple-sitemap": "^3.0.9",
    "prettier": "^2.8.8",
    "rss": "^1.2.2",
    "vue-disqus": "^5.1.0",
    "vue-social-sharing": "^4.0.0-alpha4"
  },
  "dependencies": {
    "@gtm-support/vue-gtm": "^2.2.0",
    "@headlessui/vue": "^1.7.14",
    "@heroicons/vue": "^2.0.18",
    "nuxt": "^3.6.2"
  }
}

I'm using with vite not webback
node: 16.14.0

Any suggestion? Maybe I'm missing something

Additional information

  • Would you be willing to help implement this feature?

Final checks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.