Next.js Discord

Discord Forum

Virtual hosts with Next.js and data caching?

Unanswered
Giant Angora posted this in #help-forum
Open in Discord
Avatar
Giant AngoraOP
Currently I'm building a website with Next.js that will be accessible through multiple domains, for example my Next.js server is running at 1.2.3.4 and I have both site-alpha.example and site-beta.example resolving to that IP address.

When Next.js receives it's initial GET request in the browser I'm using the next/headers helper to get the Host request header and then using that to request the required data for that website from my CMS with fetch API requests (where the Host request header is provided to as an argument in that query for data).

However, this has resulted in slow page load times because by using the next/headers helper to access to the Host header this has inadvertently opted me out of data caching according to the following documentation section.
https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#opting-out-of-data-caching

The slow page load times are because every time site-alpha.example or site-beta.example is requested from my Next.js server it is always making fetch API requests to my CMS and bypassing any caching.

What should I do in this case?

Would it be better to force-cache on all the fetch API requests made for data from the CMS?

Why does using next/headers automatically opt you out from using the data cache?

2 Replies

Avatar
Why does using next/headers automatically opt you out from using the data cache?

As stated in the documentation, it is because the function returns request data that can only be known at runtime and not anytime before.

Would it be better to force-cache on all the fetch API requests made for data from the CMS?

This would do nothing since you are fetching after the usage of headers

What should I do in this case

The hard truth is your site depends on request data to do any data fetching so the fetch will never be cached.

The only solution that I know of that will for sure work is using unstable_cache to persistently cache the data you need within your site. Just keep in mind that this is a persistent cache, so it won't ever be fresh unless you manually invalidate it with revalidatePath or revalidateTag or set time-based revalidation on the function. Not even a new build will invalidate the cache
It will also cache in development, since the behaviors are the same.