Next.js Discord

Discord Forum

Route can have searchParams—how to opt into Full Route Cache if none are provided?

Unanswered
tlmader (Patina Project) posted this in #help-forum
Open in Discord
I am new to Next, so forgive me if I am not understanding the caching entirely.

I have a page at https://www.patinaproject.com/grant-stone where load time is important, and I would like to use the Full Route Cache when search parameters are not provided.

This page optionally allows using search params to let crawlers to load additional pages of content:
https://www.patinaproject.com/grant-stone?page=2

To my understanding, simply accessing searchParams opts the page out, even if none are provided. The behavior I want is to use Full Route Cache for the routes without the page parameter.

Is there a way to accomplish this? Or a recommended way to work around it?

4 Replies

@tlmader (Patina Project) I am new to Next, so forgive me if I am not understanding the caching entirely. I have a page at https://www.patinaproject.com/grant-stone where load time is important, and I would like to use the Full Route Cache when search parameters are not provided. This page optionally allows using search params to let crawlers to load additional pages of content: https://www.patinaproject.com/grant-stone?page=2 To my understanding, simply accessing `searchParams` opts the page out, even if none are provided. The behavior I want is to use Full Route Cache for the routes without the page parameter. Is there a way to accomplish this? Or a recommended way to work around it?
you cannot. a few ways to workaround/mitigate:

1: you can opt for client-side data fetching for data that depends on searchParams. then full route cache is possible again (since you dont have to read searchParams on the server). the cons is data that depends on searchParams is no longer fetched on the server

2: you can cache the non-searchParams case in the data cache

function Page({ searchParams }) {
  // Cache CachedPage with "use cache" or unstable_cache or something like that
  if (noSearchParams) return <CachedPage />
  
  // this one is not cached
  return <Stuff data={searchParams.q} />
}


then the load time will still be minimal since the expensive part is already cached in the data cache.

3: you can have a separate page for the non-searchParams case. this page can be static. then you use middleware or next.config.js or your infra configuration to rewrite /original-page requests without search params onto /new-page.