tRPC

T

tRPC

Move Fast & Break Nothing. End-to-end typesafe APIs made easy.

Join

What are the benefits of adding db to context rather than importing it directly in the router?

As per title, the docs and most examples I've seen using TRPC put the database into context as follows, ``` import db from "../db"; export const createContext = async (opts: CreateNextContextOptions) => { ...

Calling Express `request.send` inside tRPC middleware/procedures

Hello 👋! I've been trying to introduce tRPC to our existing express codebase and I was wondering if it's possible to invoke express request.send inside my tRPC middleware or procedures. I want to avoid rewriting our entire auth layer which is unfortunately deeply coupled with the express request/response objects, and instead just call our existing express middleware functions. However I want to make sure doing so isn't going to cause any memory leaks or hanging promises or anything which could silently brick the whole server. Will the tRPC handler return or exit gracefully if the request is closed? Has anyone had experience with this? example:...
Solution:
@Alex / KATT 🐱: You can pass a fake res-object to await runJWTValidations(req, res) Example that probably needs some modification: ```ts const mockRes = {...

Extending "Meta" with downstream concat usage?

Is there a way to extend the meta when using concat and creating plugins and middleware? e.g having a plugin called permission and then requiring the meta data to extend the existing base Meta to contain a new required field e.g permission In my attempts I've just been getting "meta mismatch"...

following the trpc 11 guide on app router fails with dynamicIO on nextJS

When using trpc with nextjs@15.0.3-canary.4 with dynamicIO enabled I get the following error when trying to create a query client. Error: Route "/" used Date.now() instead of using performance or without explicitly calling await connection() beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time at io (node_modules/next/src/server/node-environment-extensions/utils.tsx:33:31) at now (node_modules/next/src/server/node-environment-extensions/date.tsx:17:9)...

Fetch once and never again?

Hey there 👋, I'm wanting to fetch some data reactionTypes once when my layout <MainLayout /> renders in Nextjs and never again because this data does not change. Currently, I have placed (what I think is) a headless component into my layout that accesses the query client then sets a staleTime: Infinity default on this specific query. Is this a dumb strategy? How might you do this differently? ```TSX...

Unsafe assignment of an error typed value

Hey guys, I'm new to tRPC so it's probably a newbie question I've a simple route creation, which I'm trying to add more methods to it but eslint is always warning about any other route I create: ```tsx import { z } from 'zod' ...
No description

Correct way to fetch trpc data on SSR and CSR

Hello, I am currently using trpc in my nextjs app router project and I am wondering what the best way of using trpc is with a mixture of SSR and CSR. The issue I'm having is that because I'm fetching the data on the server, it also fetches on the client which menas I'm making a request needlessly, and I'm not sure what the best way of dealing with this is....

Client component does not receive updated data after refetch, how to resolve?

Linked to discussion due to word limitation Thanks in advance. I appreciate the feedback https://github.com/trpc/trpc/issues/6165...

Can I respond to client from a middleware?

I have this authentication middleware that needs to refresh the access token of a JWT session, and I don't want to duplicate the logic in all procedures. How can I send a response from the middleware itself? When I do a simple return, TS gives me some errors, it seems that it expects next() as an output....

Blob as response

I know this has been mentioned couple of time but does TRPC allow returning a blob on the client from a publicProcedure. ```downloadFile: baseProcedure.mutation(async () => { const response = await ky("api/export", { headers: {...

Error handling abort on unstable_httpBatchStreamLink

When using a streaming response with unstable_httpBatchStreamLink and cancelling a request with an AbortController, the client will throw an error. The error is an instance of a generic error rather than a TRPCClientError. I'm trying to think of a solid way to swallow the abort error.

nextjs middleware trpc authentication

When I use trpc in a server action for a server component, if auth fails and throws a new TRPCError({ code: 'UNAUTHORIZED' }); in the backend, how do I wrap that in nextjs middleware? my nextjs middleware already reroutes to a 404 page if the requesting page is not found. how do I reroute to an authorized page for every server action with trpc? in middleware.ts it says that the request is getting captured at this location for some reason _nextjs_original-stack-frame...

Custom data transformer

Has anyone had any experience with custom data transformers? I'm trying to map LocalDate, LocalTime, Instant, etc. from a date & time library. Every type can be serialized to a string (the corresponding ISO format) but it's unclear to me what the best strategy is via a data transformer? Should I serialize these objects to a custom shape (e.g. { type: "LocalDate", value: "..." }) so that it's trivial to deserialize? Seems kinda redundant since the type information is already at the type level. Without a custom shape it's unclear to me how I would be able to deserialize the object given that I don't know the destination type....
Solution:
It worked just fine as described above. 👍

How to add req to Context?

I have tried multiple variations of the inner/outer context docs code, but ctx.req and ctx.res are always undefined. https://trpc.io/docs/server/context#inner-and-outer-context. In this related issue, Julius stated that the code shouldn't even work. https://github.com/trpc/trpc/issues/5344. What is the official consensus on this? If it doesn't work then how else does one add the request to context (and why is it in the docs)....
Solution:
I believe the issue was because I had created a trpc caller without passing the req object.

Any guidance on adding middleware at the router level?

I want to apply middleware across all admin routes. I could add middleware to the adminProcedure, but I'd prefer to do so at the router level. I didn't see any info in the docs. How can I accomplish this? ``` const adminRouter = router({ secretPlace: adminProcedure.query(() => 'a key'), secretPlace2: adminProcedure.query(() => 'b key')...

Sentry Profiling for TRPC

Has anyone been able to set up Sentry Profiling for TRPC? For example, being able to see how long each API route takes to resolve? We want to identify which TRPC routes are the slowest / least performant...

useQuery() integration is not passing `staleTime` to underlying query? (11.0.0-rc.593)

I'm attempting to set up persistence for my queries. As part of this, I need to set staleTime on queries to something other than 0 to tell React Query that data loaded from storage is to be considered fresh. However, this doesn't work in practice if staleTime is configured at the query level. I've managed to get persistence working correctly when configuring the query client's default options. Is there an interaction that I'm not understanding here? Any advice would be welcome, thanks!...

Getting CORS error with tRPC express adapter, locally

I've got a Vite + tRPC backend (same repo) that I'm struggling to get queries from. I'm just getting 'Failed to Fetch' on the UI and Network says it's a Cors error. Here's my trpcClient...
Solution:
I realized that I could just run the tRPC server and that also runs the client somehow — so no need for different ports and causing cors issues.
No description

trpc version 11.0.0-rc.383 breaks turbo

I was seeing a MODULE_UNPARSEABLE error when running with the latest trpc rc. I did a bisect and found 11.0.0-rc.383 to be the breaking version. 11.0.0-rc.382 works fine. Only happens when running with next dev --turbo. next dev is fine...

How to use subscription with bullmq?

How can I process the messages in the queue with bullmq in the worker and publish them on the subscription side? I can't solve it in any way. My trpc server is published on my own nodejs server. What I want to do is as follows, but we can't use yield in eventlistener. What is the right way? ...
Next