#Virtual hosts with Next.js and data caching?

3 messages · Page 1 of 1 (latest)

viscid fable
#

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?

grand dirgeBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

upbeat mantle
#

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