Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get cookie value on server in Nuxt3?

/api/show.js

export default defineEventHandler(async (event) => {
  const cookie = getCookie(event, 'jwt')

  console.log("cookie: " + cookie);
  
  return { cookie: cookie }
})

When I go to http://localhost:3000/api/show in my browser I can see the proper value on the screen and I can see the proper value logged to the console from the server.
But when I try to use it in my app, like this:

<script setup>
const { data } = await useFetch('/api/show')
console.log(data.value.cookie);
</script>

then both console logs, the one on the server and the one on the client, show undefined.
What's the logic behind that?
How can I properly get cookie value on a server in Nuxt3?

like image 902
DuchSuvaa Avatar asked Sep 20 '25 12:09

DuchSuvaa


1 Answers

Due to breaking changes now you can't

  • import useCookie from #app, #imports and h3.

Instead you should use parseCookie and setCookie imported from h3.

import { defineEventHandler, H3Event, parseCookies, setCookie } from 'h3'

to get cookies

export default defineEventHandler((event: H3Event) => {
  const cookies = parseCookies(event)
  const token = cookies?.token

to set cookies

  setCookie(event, 'token', token)

Docs: https://nuxt.com/docs/guide/directory-structure/server

like image 109
Daniel Avatar answered Sep 23 '25 13:09

Daniel