Pass the User's Session to Your API
Forwarding Headers & Cookies
During SSR, your server-side fetch is a brand-new request. To authenticate as the user, forward cookies and auth headers from the incoming request.
What you'll learn
- Read incoming request headers with useRequestHeaders
- Forward selected headers to useFetch
- Understand why server/api routes already share request context
When useFetch runs on the server during SSR, it does not automatically carry the browser’s
cookies. If your API is on a separate host (or behaves like one), you must forward auth headers
explicitly.
useRequestHeaders
<script setup lang="ts">
const headers = useRequestHeaders(['cookie', 'authorization'])
const { data: me } = await useFetch('https://api.example.com/me', {
headers
})
</script> useRequestHeaders(['cookie']) returns an object containing only the listed headers from the
incoming SSR request. On the client, it returns an empty object (the browser handles cookies
natively).
Why It Matters
Without forwarding, the SSR fetch arrives at your API with no Cookie header — the server treats
it as an anonymous request, returns the public response, and your page hydrates as if the user is
logged out. Then the client refetches, sees the user, and the page changes. Not great.
Same-Origin Proxying
If you reach your API through server/api/*.ts routes in the same Nuxt app, the request context
flows automatically — event.headers already contains the original cookies. No manual forwarding
needed:
// server/api/me.ts
export default defineEventHandler(async (event) => {
const cookie = getHeader(event, 'cookie')
return await $fetch('https://api.example.com/me', {
headers: { cookie: cookie ?? '' }
})
}) This pattern — Nuxt server route as a proxy — is a clean way to keep secrets server-side and avoid CORS.
Fetch Error Handling →