Next.js Discord

Discord Forum

App Router cache not working on server side component

Unanswered
Red wood ant posted this in #help-forum
Open in Discord
Red wood antOP
I fetch on server side component always call api route. how to use cache?

28 Replies

@ᴉuɐpɹɐɐ what is `fetchApis.dynamic` ?
Red wood antOP
fetchApis.dynamic is just return fetch(localhost:3000/${path}?...) with types.
try removing headers: ...
@ᴉuɐpɹɐɐ try removing `headers: ...`
Red wood antOP
It’s working…
but that’s just set Cookies. Why remove header working?…
@ᴉuɐpɹɐɐ what is inside `await defaultHeaders()` ?
Red wood antOP
@Red wood ant Click to see attachment
in the server you call cookies() and that probably opts out of the data cache.
its weird since you probably dont want to cache requests that rely on user request
if you want to make the server request "cacheable" then use a pregenerated cookie instead of getting it from the user (via cookies())
then you can use the next.js backend to filter out anything if the user (for example) doesnt have permission
by caching in next.js that means you allow any request to be made in the server regardless of user permission, and handling auth checks in the next.js itself against the returned cached data
so you no longer rely your backend to do the auth checks
that is the pattern you'd use if you want to opt-in into data caching
the typeof window === 'undefined part is already a step in the right direction. i like that part
@ᴉuɐpɹɐɐ in the server you call `cookies()` and that probably opts out of the data cache.
Red wood antOP
Okay i got it. I try change that.
Red wood antOP
@ᴉuɐpɹɐɐ Could I get an example code...?
@ᴉuɐpɹɐɐ which part?
Red wood antOP
How to use pregenerated cookies inside server?
here
typeof window === 'undefined' ? ''
just remove Cookie
you dont need it right?
Red wood antOP
If the cookie is removed, the data cache functions properly. But we need Cookies.
Client cookie have a authentication infos...
@Red wood ant Client cookie have a authentication infos...
your client cookie will automatically be sent to the server using fetch()
its part of how cookies works
@ᴉuɐpɹɐɐ your client cookie will automatically be sent to the server using fetch()
Red wood antOP
But sever side request not have cookies…