Cookie on ssr
I have a composable which reads cookies to get some values and do api calls when it runs on server it's unable to get cookies ( use cookie) doesn't work
useCookie should work on both client and server side in Nuxt 3. However, if you're experiencing issues, it might be due to how you're accessing or setting the cookies.useRequestHeaders to access the incoming request headers and forward them to your API calls. Here's an example:setCookie and getCookie from the h3 package in your server API routes:useRequestFetch which automatically forwards the request context and headers for server-side fetch requests:useCookie within the Nuxt context. It only works within pages, components, and plugins.useCookieuseCookieuseRequestHeaderssetCookiegetCookieh3useRequestFetchconst headers = useRequestHeaders(['cookie'])
const { data } = await useFetch('/api/me', { headers })import { defineEventHandler, setCookie, getCookie } from 'h3'
export default defineEventHandler(event => {
// Read counter cookie
let counter = getCookie(event, 'counter') || 0
// Increase counter cookie by 1
setCookie(event, 'counter', ++counter)
// Send JSON response
return { counter }
})const requestFetch = useRequestFetch()
const { data: forwarded } = await useAsyncData(() => requestFetch('/api/cookies'))