Reputation: 140
Will a .fetch() call on a initTRPC.context, server side, be deduped by the nextjs app router or not?
From nextjs docs: "Passing data between a parent layout and its children is not possible. However, you can fetch the same data in a route more than once, and React will automatically dedupe the requests without affecting performance."
From tan-stack docs: "Next.js already dedupes requests that utilize fetch(), but if you are using something else in your queryFn, or if you use a framework that does not dedupe these requests automatically, using a single queryClient as described above might make sense, despite the duplicated serialization."
Upvotes: 0
Views: 213
Reputation: 21
In my experience if you set up trpc in a next.js project, at least with app router, serverside requests will not be deduped.
Minimal working example app for testing can be achieved with npm create t3-app@latest
.
However, I did find a simple solution to this issue. We can use react cache()
to do the deduping manually.
I normally do this in a separate file and then just import the cached data in all the react server components I need, including layouts.
This helps particularly with sharing data between layouts and pages, since there is no way in Next.js to fetch the data only once in the layout and pass it as props to the children pages.
Example:
import { api } from '~/trpc/server'
import { cache } from 'react'
// example assumes this exists in your trpc router
export const userProfile = cache(api.user.profile.query)
Then in my RSC file:
import {userProfile} from '...'
export const MyReactServerComponent: React.FC = async () => {
const user = await userProfile
return <div>{user.name}</div>
}
Upvotes: 1