You can use useRequestFetch to forward the request context and headers when making server-side fetch requests.
When making a client-side fetch request, the browser automatically sends the necessary headers. However, when making a request during server-side rendering, due to security considerations, we need to forward the headers manually.
transfer-encoding, connection, keep-alive, upgrade, expect, host, acceptuseFetch composable uses useRequestFetch under the hood to automatically forward the request context and headers.<script setup lang="ts">
// This will forward the user's headers to the `/api/cookies` event handler
// Result: { cookies: { foo: 'bar' } }
const requestFetch = useRequestFetch()
const { data: forwarded } = await useAsyncData(() => requestFetch('/api/cookies'))
// This will NOT forward anything
// Result: { cookies: {} }
const { data: notForwarded } = await useAsyncData((_nuxtApp, { signal }) => $fetch('/api/cookies', { signal }))
</script>
export default defineEventHandler((event) => {
const cookies = parseCookies(event)
return { cookies }
})
useRequestFetch will behave just like regular $fetch.