Next.js Discord

Discord Forum

Sending cookies through server components

Answered
Siamese Crocodile posted this in #help-forum
Open in Discord
Avatar
Siamese CrocodileOP
Hi, I've an external backend that sets a cookie and It's set properly -> I can access it using nextjs cookies(). The problem is that when I want to fetch some user specific data using fetch with credentials include the cookies that I console log inside server component are not being sent to the external api.

const sessionId = (await cookies()).get('sessionId')?.value

console.log("sessionId") -> 'someuniqueid123'

fetch("my-external-api.com", { credentials: 'include'} ) // This session id above is not used for this request so we get 401


return <div>Server component</div>
Answered by B33fb0n3
you are right, cookies won't be directly forwarded. You need to place the cookies extra inside your fetch request
View full answer

5 Replies

Answer
Avatar
Siamese CrocodileOP
@B33fb0n3 that sucks - what if cookie has an expiration date and I will be pasing only the value.

Also the api would differ - when I do client side mutations I dont have to include credentials because cookies are sent automatically

When I am fetching some static data that doesnt require authentication I dont need to use cookies with fetch

But when I am fetching some user specific data i need to read cookies and set them manually in fetch


Is it the correct approach?
Avatar
Siamese CrocodileOP
Ty
Avatar
happy to help