Back to articles
tRPC Has a Free API — Here's How to Build End-to-End Type-Safe APIs

tRPC Has a Free API — Here's How to Build End-to-End Type-Safe APIs

via Dev.to ReactAlex Spinov

tRPC lets you build fully type-safe APIs without schemas, code generation, or runtime validation overhead. Types flow from your backend to frontend automatically. Installation npm install @trpc/server @trpc/client @trpc/react-query @tanstack/react-query zod Server Setup import { initTRPC } from " @trpc/server " ; import { z } from " zod " ; const t = initTRPC . create (); const router = t . router ; const publicProcedure = t . procedure ; const appRouter = router ({ // Query — get data hello : publicProcedure . input ( z . object ({ name : z . string () })) . query (({ input }) => { return { greeting : `Hello, ${ input . name } !` }; }), // Query — list items posts : publicProcedure . input ( z . object ({ limit : z . number (). default ( 10 ) })) . query ( async ({ input }) => { return db . post . findMany ({ take : input . limit , orderBy : { createdAt : " desc " } }); }), // Mutation — create item createPost : publicProcedure . input ( z . object ({ title : z . string (). min ( 1 ).

Continue reading on Dev.to React

Opens in a new tab

Read Full Article
2 views

Related Articles