tRPC
tRPC is a TypeScript RPC framework.
A minimal example
We will use bun for simplicity, bun can be installed via brew install bun.
Install trpc:
bun add @trpc/server@next @trpc/client@next
Server
Add server.ts:
import { initTRPC } from '@trpc/server'
import { createHTTPServer } from '@trpc/server/adapters/standalone'
const { router, procedure } = initTRPC.create()
const appRouter = router({
userList: procedure.query(async () => {
return [{ name: "Alice" }, { name: "Bob" }]
}),
})
export type AppRouter = typeof appRouter
const server = createHTTPServer({
router: appRouter,
})
server.listen(3000)
Client
Add client.ts:
import { createTRPCClient, httpBatchLink } from '@trpc/client'
import type { AppRouter } from './server'
const trpc = createTRPCClient<AppRouter>({
links: [
httpBatchLink({
url: 'http://localhost:3000',
}),
],
})
const users = await trpc.userList.query()
console.log(users)
Run
Start the server:
bun server.ts
Run the client in another terminal:
bun client.ts
Why tRPC
tRPC offers exceptional developer experience (DX) with a fully typed API for clients. It is also easier to set up compared to gRPC. Overall, it's an ideal choice for a pure TypeScript stack.