/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?
Due to breaking changes now you can't
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With