Next.js Discord

Discord Forum

Nextjs 14 Cache in production

Unanswered
Yellowfin tuna posted this in #help-forum
Open in Discord
Yellowfin tunaOP
Hello!

From what I understand about the Cache system that Nextjs uses, on one hand we have the “Request Memoization”, which is more of a “dedupe” than a cache. With this functionality we can execute several identical fetches in our React tree, or on the same page, that only one will be executed, the others will use the cache of the first fetch executed.

Then there is the Data Cache, which is a cache that DOES persist across requests. Therefore I can have the same fetch, on different pages of my application, and only one will be executed, the others will use the cache.

Now I want to make use of these caches. For this I have this function:

export const getUserById = async ({ userId, token }: { userId: string; token: string }) => { const userRawResponse = await fetch(${process.env.NEXT_PUBLIC_API_URL}/api/v1/user/${userId}, { cache: "force-cache", headers: { Authorization:Bearer ${token}, }, next: { tags: ["user-by-id"], }, }); const userResponse: ApiResponse<User> = await userRawResponse.json(); const user = userResponse.data; return user; };

To get the token, I previously make a call to cookies(). From what I understand using “dynamic functions” such as cookies or headers, can opt out of the cache, but for the “Full Route Cache”. Therefore this fetch should be cached in the “Data Cache”.

This works perfectly for me locally, but when I deploy to Vercel, the cache is never set. Every time I reload the page a new call is made to my external API.

I don’t know if I’m making a mistake somewhere, or if I’ve misunderstood the Caching documentation. Does anyone know what might be happening?

1 Reply

Yellowfin tunaOP
So after some more investigation, I found that maybe I shouldn't cache user-specific data at all. Still don't know why in localhost is cached, and in prod is not.