logo

Setting up tRPC with React and Express JS

MU

Muhammad Usama

Published on February 19, 2023

Setting up tRPC with React and Express JS

Setting up tRPC with React and Express JS

Building web applications with React and Express.js can be a complex and time-consuming process, especially when it comes to setting up API endpoints and managing data flow between the client and server. However, by using tRPC, a lightweight and easy-to-use framework, developers can simplify this process and improve performance.


Initialize Project

mkdir trpc-react-express
cd trpc-react-express
yarn init -y

We will be using yarn workspaces to set up a monorepo, but you can use other package managers too.

Install dev dependencies:

yarn add concurrently wsrun -D

Update your root package.json to manage server and client scripts with workspaces.


Server Package

Create a packages/server folder:

mkdir -p packages/server
cd packages/server
yarn init -y
yarn add express zod cors @trpc/server
yarn add @types/cors @types/express @types/node ts-node-dev typescript -D

Setup tsconfig.json, add context.ts, trpc.ts, and your first router (user.ts).
Finally, wire everything together in app.ts with Express and tRPC.


Client Package

In packages, create a React/Next.js app:

yarn create next-app client
cd client
yarn add @trpc/client @trpc/react-query @trpc/server @tanstack/react-query

Add your server as a dependency in client’s package.json, then configure:

  • utils/trpc.ts → create TRPC client
  • utils/trpc-provider.tsx → wrap app with React Query + TRPC provider

Usage example:

import { api } from "@/utils/trpc";

export default function Home() {
  const { data, isLoading, error } = api.user.sayMyName.useQuery({ name: "Usama" });
  if (error) return <div>Error</div>;
  if (isLoading) return <div>Loading...</div>;
  return <div>{data.name}</div>;
}

Run Project

From the root, run:

yarn dev:parallel

Your monorepo now runs both server + client with type-safe APIs via tRPC. 🚀

Ready to Start Something Great?

Our experts love collaborating with brands that think big. Let’s connect and explore how we can build something amazing together.

Setting up tRPC with React and Express JS | Zauf Labs