Usage with Express.js

Example app

DescriptionURLLinks
Express server & procedure calls with node.js.n/a

How to add tRPC to existing Express.js project

1. Install deps

  1. yarn add @trpc/server zod

Zod isn’t a required dependency, but it’s used in the sample router below.

2. Create a tRPC router

Implement your tRPC router. A sample router is given below:

server.ts

  1. import * as trpc from '@trpc/server';
  2. import { z } from 'zod';
  3. const appRouter = trpc
  4. .router()
  5. .query('getUser', {
  6. input: z.string(),
  7. async resolve(req) {
  8. req.input; // string
  9. return { id: req.input, name: 'Bilbo' };
  10. },
  11. })
  12. .mutation('createUser', {
  13. // validate input with Zod
  14. input: z.object({ name: z.string().min(5) }),
  15. async resolve(req) {
  16. // use your ORM of choice
  17. return await UserModel.create({
  18. data: req.input,
  19. });
  20. },
  21. });
  22. // export type definition of API
  23. export type AppRouter = typeof appRouter;

If your router file starts getting too big, split your router into several subrouters each implemented in its own file. Then merge them into a single root appRouter.

3. Use the Express.js adapter

tRPC includes an adapter for Express.js out of the box. This adapter lets you convert your tRPC router into an Express.js middleware.

server.ts

  1. import * as trpcExpress from '@trpc/server/adapters/express';
  2. const appRouter = /* ... */;
  3. const app = express();
  4. // created for each request
  5. const createContext = ({
  6. req,
  7. res,
  8. }: trpcExpress.CreateExpressContextOptions) => ({}) // no context
  9. type Context = trpc.inferAsyncReturnType<typeof createContext>;
  10. app.use(
  11. '/trpc',
  12. trpcExpress.createExpressMiddleware({
  13. router: appRouter,
  14. createContext,
  15. })
  16. );
  17. app.listen(4000);

Your endpoints are now available via HTTP!

EndpointHTTP URI
getUserGET http://localhost:4000/trpc/getUser?input=INPUT

where INPUT is a URI-encoded JSON string.
createUserPOST http://localhost:4000/trpc/createUser

with req.body of type {name: string}