0

When trying to set a cookie with cookie-universal-nuxt in my router middleware I get the error:

TypeError: Cannot read properties of undefined (reading 'set')

What is causing this?

nuxt.config.js

modules: [
    'cookie-universal-nuxt',
],

router.js (router middleware)

export default async ({ app }) => {

    app.$cookies.set('cookie-name', 'cookie-value', {
        path: '/',
        maxAge: 60 * 60 * 24 * 7
    });
}

I tried logging in different places:

When I run console.log(app.$cookies) in the router it returns undefined.

When I run it in a component (so: console.log(this.app.$cookies)) it returns Cannot read properties of undefined (reading 'app'). I am using the composition-api so I also tried console.log(context.root.$cookies) but this also returns undefined.

3
  • Your code looks fine, so I'd encourage you to share some more information. It looks like $cookies is not being added to your nuxt context for some reason- can you access it from anywhere else within your app? Try "this.$cookies" for example in a component. Commented Mar 29, 2022 at 12:26
  • When console.log(app.$cookies) it returns undefined. Commented Mar 29, 2022 at 12:32
  • Yes, but where in your app are you running console.log(app.$cookies)? For example, within the script tags of a component you'd need to refer to this.app.$cookies. Elsewhere in your app, this may not refer to the root Vue instance on which app and $cookies etc should be available. Please provide more detail :) Commented Mar 29, 2022 at 12:38

1 Answer 1

1

solution:

nuxt.config.js

  modules: [
    ['cookie-universal-nuxt', { alias: 'cookiz' }]
  ],

router.js (router middleware)

export default async ({ app }) => {
    app.$cookiz.set('cookie-name', 'cookie-value', {
        path: '/',
        maxAge: 60 * 60 * 24 * 7
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.