Daniel Reina
Daniel Reina

Reputation: 6347

Skip SSR in NextJS when I already have the data cached and not stale in the client

I'm using NextJS with TanStack Query (formerly ReactQuery). TanStack Query acts as a cache between my NextJS app and the data stored in the backend.

I was previously doing SSR only, but I'm complementing it with TanStack Query for optimistic updates. I previously needed to fetch data on getServerSideProps for every "detail" page, but now I'm thinking that I could skip some of those fetches since I already have the data in the cache and it's still fresh.

For example. Let's say we have a TODO app. When I visit /todo/id_1 for the first time, it's nice to have SSR to send the page already rendered to the client. If I go somewhere else, and come back to /todo/id_1, I know for a fact that the contents of that TODO hasn't changed, but I still need to go through SSR.

Would there be a way to skip SSR in that case?

I was hoping I could to something like the following:

<Link href={`/todo/${id}`} skipSsr={cachedTodo[id].notStale} />

Upvotes: 3

Views: 2293

Answers (1)

TkDodo
TkDodo

Reputation: 28803

NextJs will always call getServerSideProps if the url changes. As mentioned in the comments, shallow routing does not work if the url actually changes.

I think there are a couple of ways around this:

  1. set a cache-control: max-age on the response with the time of caching that you want. That way, the request will be made, but it will not hit your server, but come from the browser cache instead. As an advantage, those fetches will also succeed while you're offline.
  2. instruct next to not make the query if the request comes from a client transition. There is an open discussion about this: Add option to disable getServerSideProps on client-side navigation shallow routing doesn't really solve it, so it seems you have to make the request and then check if it comes from SSR or not. This comment has the best workaround I guess ?
  3. use incremental static site regeneration. It basically makes your page static, but it revalidates after a certain time if a request comes in.

Upvotes: 2

Related Questions