this post was submitted on 08 Apr 2024
6 points (100.0% liked)

JavaScript

1700 readers
5 users here now

founded 1 year ago
MODERATORS
 

Hi! I'm hoping someone can point me to best practices in regards to API cookies, NextJS, and SSR.

What I'm encountering is that I'm calling an external API that is trying to set some cookies on the browser. This works when the call is made directly from the browser to the API. However, if the API call is made from the SSR function, then the cookie data never makes it to the browser.

In this way the cookie is thrown away and never sent for follow-up requests.

What is the best way to handle these API cookies when using SSR? Is there a way to have NextJS pass them back to the browser or remember them for subsequent calls. Any advice, links, or videos would be very helpful.

top 5 comments
sorted by: hot top controversial new old
[–] not_woody_shaw@lemmy.world 2 points 5 months ago

Sounds like you found a thing that needs to happen on the client side.

[–] Empathy@beehaw.org 1 points 5 months ago* (last edited 5 months ago) (1 children)

Are you using NextJS with the app router, or with the pages router?

[–] Fyzbo@programming.dev 1 points 5 months ago (1 children)

App router, where the directory structure controls the url.

[–] Empathy@beehaw.org 2 points 5 months ago

For both frameworks, the directory structure controls the URL unless there's an exception I'm unaware of.

One way to forward the cookie may be to read cookies from the API response headers and write them using the following documentation: https://nextjs.org/docs/app/api-reference/functions/cookies

[–] desmosthenes@lemmy.world 1 points 3 months ago

whereever you drop/manipulate the cookie (assuming its within your control) is where you'd have to add additional logic to handle that data SSR. if that external source is beyond your control you likely wont be able to sniff that cookie out (you can stack iframes potentially) and essentially 'monitor' the contents but not sure this is practical/effective