#Nuxt 3 `setCookie` not working
20 messages · Page 1 of 1 (latest)
Hi, what is not working? I'm using it without problems... (It's het cookie that doesn't always return it, IMO, but that's a different story)
You 'just' pass it the event, the name and the value, right? And optionally some settings. But the cookie won't be set during the event handler, I think, so you cannot read it in the same handler as you're strong it in...
Yes pretty much like this.
defineEventHandler(event => {
setCookie(event, 'cookie_name', 'test_value', { httpOnly: true })
})
But the cookie won't be set during the event handler
Isn't setCookie supposed to be used on defineEventHandler?
@plain sky Have you checked out thed docs at https://nuxt.com/docs/api/composables/use-cookie#handling-cookies-in-api-routes ?
So can you explain what you want to archive and what exactly is not working? setCookie means that when the response is done and gets back to the client, the client will use this cookie and you can access it via useCookie. But you can't use a cookie you just set in the same event handler, like @ebon plover said.
Actually, I want to set http only cookie from the server-side.
So, I expect this script will set cookie from the server-side and the cookie will be visible in the browser dev tools with correct name, value, and attributes.
defineEventHandler(event => {
setCookie(event, 'cookie_name', 'test_value', { httpOnly: true })
})
But, after run this script, the cookie does not appear in browser dev tools.
Am I missing something?
@plain sky Ah yeah. The code looks fine. can you send the full code of the event handler?
I use this simple script actually:
defineEventHandler(event => {
setCookie(event, 'cookie_name', 'test_value', { httpOnly: true })
})
Seems like you’re missing https://nuxt.com/docs/guide/directory-structure/server#example export default
Is that file located in /server/api? Or how do you call the endpoint
Adding export default seems does not work either.
Is that file located in /server/api? Or how do you call the endpoint
Yes. /server/api/hello.ts. I call that API using useFetch:
await useFetch('/api/hello')
Not sure, whether it's needed, but you also do not have an age or expires option set, although they should be optional... The h3 documentation is fairly sparse on defaults, at the moment. I use the following:
setCookie(event, ACCESS_TOKEN_NAME, accessToken, {
httpOnly: true,
secure: false, // Need to make this dependent on the environment, should be true in production!!
maxAge: 60 * 60,
sameSite: "strict",
path: "/api",
});
I've tried your code but it doesn't work. Does it work on your local machine?
Stuck with same issue, i allow my self to reply
@plain sky
have you managed to get it to work ?
Nope.
I think it's working now with Nuxt 3.2.0.
useFetch is now integrated with event.$fetch, meaning cookies and context are now passed to api requests automagically within internal requests.