anton.johansson
anton.johansson15mo ago

Next.js + tRPC, multitenancy, access Next.js Router when setting tRPC headers

Hey all! I'm writing a multi-tenant solution. Most Next.js pages lie under the /pages/[tenantKey]/ path. The tenantKey describes which tenant we are working with at the moment. I'm messing around with Next.js + tRPC, and I would love to be able to access the Next.js Router (to access the tenantKey) in a generic way when accessing the tRPC client. Using the tenantKey in the path, I could automatically send a header, X-Tenant-Key, that the server side of tRPC could look at when generating the appropriate context. I'm thinking some React hook or something for this:
const useTRPC = () => {
const {query} = useRouter();
const tenantKey = {query};
// somehow create trpc client with the header `X-Tenant-Key: tenantKey`
return trpc;
}
const useTRPC = () => {
const {query} = useRouter();
const tenantKey = {query};
// somehow create trpc client with the header `X-Tenant-Key: tenantKey`
return trpc;
}
I also want to combine this with React Query of course, so I can properly get the useQuery(...) features. Using it would be like this:
const trpc = useTRPC();
const result = trpc.myNamespace.myProcedure.useQuery("my-input-parameter");
const trpc = useTRPC();
const result = trpc.myNamespace.myProcedure.useQuery("my-input-parameter");
Does anyone have any pointers? Is this possible to achieve without re-creating the @trpc/next library from scratch? 😄
1 Reply
anton.johansson
anton.johansson15mo ago
I'm guessing I could skip @trpc/next and just go for @trpc/react-query directly.