skylerdj
skylerdj4w ago

Can i use a single trpc proxy client in NextJS 12?

Hey guys quick question if anyone is around. Are there any issues with defining a trpc proxy client once in nextjs pages router and then reusing it in client components by manually passing it to a useQuery? Unfortunately our backend team has created multiple trpc routers and we still haven't upgraded from react-router v3, so the trpc-react-query integration isn't a high priority for us, but will there be any caching or request sharing issues when using a single trpc proxy client?
// define this once in src/trpc.ts
export const trpc = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: "my-remote-api-url",
headers: async () => {
// this is coming from a recoil atom
const token = await getToken();
return GetHeaders(token);
},
}),
],
});

// some component or hook in the app
const useMyQuery = () => {
return useQuery({
queryKey: ["my-query"],
queryFn: () => trcp.path.to.endpoint.query(someArgs)
})
}
// define this once in src/trpc.ts
export const trpc = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: "my-remote-api-url",
headers: async () => {
// this is coming from a recoil atom
const token = await getToken();
return GetHeaders(token);
},
}),
],
});

// some component or hook in the app
const useMyQuery = () => {
return useQuery({
queryKey: ["my-query"],
queryFn: () => trcp.path.to.endpoint.query(someArgs)
})
}
2 Replies
tyler4949
tyler49493w ago
If youre using pages router still (I think you are in v12), as long as you have a single <QueryClientProvider /> wrapping your app, you are fine to use a single trpc instance. Heres an example I have: https://github.com/tylerpashigian/t3-recipe-book/blob/main/src/utils/api.ts#L21 I am using createTRPCNext() instead of createTRPCProxyClient(), but looks similar enough.
skylerdj
skylerdjOP3w ago
I checked your code and yeah we create a query client once in _app.page.tsx. Thank you for your reply 🙏

Did you find this page helpful?