,

Guide to implementing tRPC in an ExpressJS and React project with Prisma and tailwind css

Posted by


tRPC is a modern and efficient way to build APIs in TypeScript. It provides a type-safe way to define your API routes and payloads, by utilizing your backend code directly in your frontend code. In this tutorial, we will walk through the process of setting up tRPC with ExpressJS on the backend, along with Prisma for database handling, and React on the frontend. Additionally, we will be using Tailwind CSS for styling.

Step 1: Setting up the Backend with ExpressJS and tRPC
First, create a new folder for your project and navigate into it in your terminal. Run the following commands to initiate a new Node.js project and install the required dependencies:

npm init -y
npm install express trpc @trpc/server @trpc/client prisma @prisma/client sqlite

Create a new file called server.ts and add the following code to set up ExpressJS with tRPC:

import express from 'express';
import { createRouter } from '@trpc/server';
import { prisma } from '@prisma/client';

const app = express();
const port = 3001;

const router = createRouter<{ prisma: typeof prisma }>({
  prisma,
});

app.use(express.json());
app.use(router);

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

Step 2: Setting up Prisma for Database Handling
Next, we need to set up Prisma to handle our database interactions. Run the following command in your terminal to initiate a new Prisma project:

npx prisma init

Follow the instructions to create a new SQLite database and generate the Prisma client. Next, update your Prisma schema file (prisma/schema.prisma) with the following model definition:

model User {
  id Int @id @default(autoincrement())
  name String
}

Now, deploy your Prisma schema by running the following command in your terminal:

npx prisma db push

Step 3: Setting up the Frontend with React and tRPC Client
Create a new folder called client in your project directory and navigate into it. Run the following commands to initialize a new React application and install the required dependencies:

npx create-react-app .
npm install @trpc/client @trpc/react

Create a new file called trpc.ts and add the following code to set up the tRPC client for the frontend:

import { createReactQueryHooks, createTRPCClient } from '@trpc/client';

export const trpc = createTRPCClient({
  url: 'http://localhost:3001',
});

export const trpcHooks = createReactQueryHooks(trpc);

Step 4: Styling with Tailwind CSS
To add Tailwind CSS to your project, run the following command in your terminal:

npm install tailwindcss@latest postcss@latest autoprefixer@latest @tailwindcss/forms @tailwindcss/typography

Next, create a new file called index.css in the src directory of your client folder and add the following Tailwind CSS imports:

@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';

Update your index.js file in the src directory to import the index.css file:

import './index.css';

Step 5: Building the Frontend
Now that we have set up the backend and frontend, we can begin building our application. Create a new component called UserList.jsx in the src/components directory of your client folder and add the following code:

import React from 'react';
import { trpcHooks } from '../trpc';

const UserList = () => {
  const { data: users } = trpcHooks.useQuery(['users.list'], {});

  return (
    <div>
      <h1>User List</h1>
      {users && users.map(user => (
        <div key={user.id}>{user.name}</div>
      ))}
    </div>
  );
};

export default UserList;

In the App.js file in the src directory of your client folder, import the UserList component and add it to your application:

import React from 'react';
import UserList from './components/UserList';

function App() {
  return (
    <div>
      <h1>Hello World</h1>
      <UserList />
    </div>
  );
}

export default App;

Step 6: Running the Application
To start the backend server, run the following command in your project directory:

node server.ts

To start the frontend server, run the following command in the client directory of your project:

npm start

Your application should now be up and running. You can visit http://localhost:3000 in your browser to see the frontend interface, which should display a list of users fetched from the backend using tRPC.

In conclusion, this tutorial has demonstrated how to set up tRPC with ExpressJS on the backend, along with Prisma for database handling, and React on the frontend. Additionally, we have utilized Tailwind CSS for styling. By following these steps, you can build a modern and efficient web application with a type-safe API using tRPC.

0 0 votes
Article Rating

Leave a Reply

22 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@AnweshGangula
1 hour ago

Looks like trpc works only with npm version 7.24.2 and above only since npm workspaces are introduced then

@AnweshGangula
1 hour ago

I'm using a windows machine and i'm not able to run the `npm run dev` command in the root package.json. Its is only running the first command from the script

@remarkablejames
1 hour ago

Man I wish all tutors were like you. focusing on the main topic without wavering in irrelevant stuff. loved it when you said "this is not a prisma tutorial that's why i won't explain prisma code"

@seniordotdev
1 hour ago

How can I deploy this project? Please also make a video about deploying.

@romulie
1 hour ago

Very nice video man, thank you. But how can we put this in production? Its prossible to put in vercel? or a shared host like hostinger?

@stevejobs7663
1 hour ago

Good job!

@rishrauz3469
1 hour ago

when you fetch the list of todos and mapping directly through it, should n't we use state to save the response and map through that state in react?

@misterhtmlcss
1 hour ago

Yours was one of the best, the only thing I think I could say that may be useful feedback is that this is mostly a good tutorial for someone who is a stronger developer (I'm decent) and they need sort of a tour of the tooling, but not to learn too much. If someone is junior or lower intermediate then I think my advice is possibly very valid in my last statement.

For more context, I think for example that when you are setting up your front and backend you could/should stop and take a moment periodically to explain why and how that works. Even draw backs would be good or how it is different than x common JS tech stack. This gives some openings for more junior people to recognize questions they need to ask and some idea how to go about searching for that knowledge too. Also destructuring is another area that IMO I generally think is a bad choice because destructuring ({ input }) abstracts away what is happening and reduces clarity for newbies and newer devs, which I think this video was mostly geared towards. For me it was a little off putting, but I know how to resolve my question in about 5seconds and I also know the question to ask myself when I see that. This is non-obvious to others IMO.

Let me end by saying my feedback is not a tear down. I have taken the time to give this feedback only as a way to pay forward your gift to me by creating this video and other than a Like I have no other way of truly being supportive. This is my way as a viewer of thanking you for doing such a great job from which I have benefitted and I really appreciate your efforts.

Oh one last thing. I really found your pace was good and your clarity of enunciation/clarity when speaking is top notch.

@shourovahmed8230
1 hour ago

took around 5 hours to successfully complete this project

@AvinashSingh-tr5vt
1 hour ago

Thanks for awesome content, could you please make a video for deployment of trpc app?

@nakshatrasingh6933
1 hour ago

can we use react native instead of vite?

@raymondmichael4987
1 hour ago

for some reasons, server is not running getting error on frontend; just cloned the repo- starter

@adehenry9591
1 hour ago

Welldone for the good job, please how can we connect tRPC with NextJS 13.2 (using the new app directory)

@bernadinadimitt3971
1 hour ago

Promo sm

@BibhushanThapa
1 hour ago

Can we connect this tRPC server to Next Js app?
I am having hard time connecting tRPC server with express adapter to Nextjs. I followed the documentation and Next js is not accepting AppRouter.

@RIAN8835
1 hour ago

can you please make video on how to import 1 million data export with few aggregation pipelines with nodejs

@abdelilahou2822
1 hour ago

U doing gooood job in those thumbnail bruv They really look good lets say that they are the main reasing i subed and I think that your tuts are good too

@chanmyaemaung
1 hour ago

It's private mode for your repository. To look at the basic codes structure, could you kindly open as public?

@ramsem5151
1 hour ago

Very Nice sir,
Please make a new tool using react js. your projects are amazing and also very helpful for resume

@0xNETCAT
1 hour ago

Great explanations,
Helped me out quite a bit!
Thanks

22
0
Would love your thoughts, please comment.x
()
x