Storing cookies

I am trying to set cookies on my adonis app using
response.cookie('cartTotal', 20)
and accessing it on another controller using
response.cookie('cartTotal')

the later returns undefined value, what am doing wrong

here is my code

async setcookie({params, response}){
    try {
        const {id} = params

        response.cookie('pageViews', 'pageViews')

        return response.json({
           completed: true
        })

    } catch (error) {
        return response.json({
          alert: {
                type: 'info',
                title: 'Internal Error!',
                message: 'Please try again later.',
                ButtonText: 'Ok'
            }
        })
    }
}

and accessing it like this

async showcookie({auth,response,view,session, request}) {
    console.log(request.cookie('pageViews'))
}

my session.js file in config folder looks like this

cookie: {
    httpOnly: true,
    domain: 'dev.local',
    sameSite: false,
    path: '/'
  },

hello,

I see a typo in your code:

async showcookie({auth,response,view,session, request}) {
    console.log(request.cookie('pageViews)) // <- you are missing a ' sign
}

it should be:

async showcookie({auth,response,view,session, request}) {
    console.log(request.cookie('pageViews'))
}

correct this and try again to see if everything is ok

my bad that is just a typing error. still wont work.

It’s hard to tell, since it’s not clear when showCookie and setCookie methods are called.

Can you share the routes for them too?

@virk the cookies is being set via post method and shown via get method.

@fredrickreuben Have you tried to explicitly set the path option ? It turns out that setting the Path option is important when sending cookies in an AJAX request.

response.cookie('cookie-name', 'My Cookie', { httpOnly: true, path: '/' })

Hello @fredrickreuben

I’m currently experiencing the same issue. The cookie created is not persisted and cannot be accessed inside my middleware.

Please did you finally figure out what the problem was and found a solution to this?

Hello, I’m not sur that is the best method. But I make a global middleware and I make the request.cookie before and after the " await next()" function. I push the cookie into the header with request.header(). And I can receive my cookie in my full app even if I refresh the browser. The middleware is just use for get and set cookie.I do that for get a token into a cookie with a login function.