Next.js Discord

Discord Forum

Headers/cookies when using `fetch` from a server component?

Answered
Abyssinian posted this in #help-forum
Open in Discord
AbyssinianOP
Cookies and/or headers don’t get forwarded on when using fetch from a server component.

The workaround seems to be to re-pass them on fetch(url, { headers: headers() }). Is this considered a bug, am I doing it wrong?
Answered by Clown
I am pretty sure this is intended behavior. If you need to use headers, you need to create them and pass them.
View full answer

10 Replies

Oriental
Hey Ben. What server are you making the fetch requests to?
Is it your own API?
Answer
Oriental
Yes, I wouldn't expect it to work automatically. We also want to be careful calling your own edge functions through fetch like this.
Which would be a situation where you might want to forward cookies.
AbyssinianOP
I’m calling the internal Next API routes and proxying them through to our own API (attaching a HTTP only cookie value as a bearer token).
I mean it’s not too much trouble to pass the headers each time, just a gotcha the team will have to be aware of.
@Abyssinian I mean it’s not too much trouble to pass the headers each time, just a gotcha the team will have to be aware of.
This is intentional. You don’t want to forward user jwt to your logging service automatically right?
This is not a gotcha, just intended behaviour
Similar to when you do a curl from your terminal: no headers or cookies are added automatically. You have to add them yourself if you need to.