TkDodo 🔮
TkDodo 🔮14mo ago

adding information to the QueryKey that is not part of the procedure input

we have the situation that we have our trpc routes read some specific information from the browsesr url. In our case, it's the ID of the workspace the user is currently on. We use that information on the server to send API requests to other services. Now we'd want to automatically add this information to the cache key, because the same route should return different information for different workspace IDs, and since users can switch workspaces, showing stale data from an old workspace is not good. What we can do right now is add the workspaceId as a required input to each route, read it on the frontend with a custom hook and provide it as input. That works but is a bit cumbersome: We know that the url will always contain the id, and we know how to read from it on the server. So is there a way to centrally add that information to the cache key? My idea was to maybe create a custom header that we add centrally, but as far as I can see, custom headers are also not added to the queryKey... Maybe I'm missing some kind of middleware on the client to add something to the key?
Solution:
Yeah this is suggested periodically, and I agree there's something a little awkward for type-safe cross-cutting concerns in tRPC, since headers are global and inputs can get repetitive, but adding to the input is the canonical way to achieve this because that way the input on the server has access to this. tRPC just isn't really a HTTP server so reading the URIs which I guess NextJS might have access to isn't really a 1st class concern Maybe there's something we could do around router-level inputs that are shared and can be set in a scoped way on the client, like orgScopedProjects = trpc.projects.setInputs({ organisationId })...
Jump to solution
3 Replies
Solution
Nick
Nick14mo ago
Yeah this is suggested periodically, and I agree there's something a little awkward for type-safe cross-cutting concerns in tRPC, since headers are global and inputs can get repetitive, but adding to the input is the canonical way to achieve this because that way the input on the server has access to this. tRPC just isn't really a HTTP server so reading the URIs which I guess NextJS might have access to isn't really a 1st class concern Maybe there's something we could do around router-level inputs that are shared and can be set in a scoped way on the client, like orgScopedProjects = trpc.projects.setInputs({ organisationId }) then orgScopedProjects.list.useQuery()
Nick
Nick14mo ago
Feels like potentially a lot of complexity to be adding though
TkDodo 🔮
TkDodo 🔮OP14mo ago
thanks for your insights, greatly appreciated 🙏 I just brought this topic up in our architecture meeting and we agreed that explicitly passing it as input is the best way, so we'll do that.