Home » How to build a Full-Stack Application with React, Prisma, and TypeScript

In the world of modern web development, creating full-stack applications demands efficient tools and technologies. React.js has emerged as a popular front-end library for building user interfaces, while Prisma offers a robust ORM (Object-Relational Mapping) solution for interacting with databases. Combining these technologies along with TypeScript, a statically typed superset of JavaScript, can streamline the development process and enhance code quality. In this comprehensive guide, we’ll explore how to harness the power of React, Prisma, and TypeScript to build a full-stack application.

Setting Up the Environment

Before diving into development, let’s set up our environment. Ensure you have Node.js and npm (Node Package Manager) installed on your machine. We’ll be using npm to manage dependencies and run scripts.

1.Create a new directory for your project:

mkdir react-prisma-app
cd react-prisma-app

1.Initialize a new Node.js project

npm init -y

1.Install necessary dependencies:

npm install react react-dom prisma typescript @prisma/client

1.Initialize a TypeScript configuration file:

npx tsc --init

Building the Backend with Prisma:

Prisma simplifies database access by providing a type-safe database client. Let’s start by defining our database schema and generating a Prisma client.

1.Define your database schema in ‘schema.prisma’:

// schema.prisma
datasource db {
  provider = "sqlite"
  url      = "file:./dev.db"
}

generator client {
  provider = "prisma-client-js"
}

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

1.Generate a Prisma client:

npx prisma generate

Now,let’s create a basic Express.js server to interact with our Prisma client:

// server.ts
import express from 'express';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();
const app = express();
const port = 3000;

app.use(express.json());

app.get('/users', async (req, res) => {
  const users = await prisma.user.findMany();
  res.json(users);
});

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

Run the server:

node server.js

Setting Up the Frontend with React:

With the backend in place, let’s create a React frontend to interact with our server.

1.Create a new React app:

npx create-react-app client
cd client

Install Axios for making HTTP  requests:

npm install axios

Replace ‘src/App.js’ content with the following:

// src/App.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';

function App() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    axios.get('/users')
      .then(res => {
        setUsers(res.data);
      })
      .catch(err => {
        console.error('Error fetching users:', err);
      });
  }, []);

  return (
    <div>
      <h1>Users</h1>
      <ul>
        {users.map(user => (
          <li key={user.id}>{user.name} - {user.email}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;

1.Start the React development server:

npm start

Conclusion

In this article, we’ve covered the process of building a full-stack application using React, Prisma, and TypeScript. We set up the backend with Prisma to interact with a SQLite database and created a frontend with React to consume data from the backend. By leveraging the power of these technologies, developers can create scalable and maintainable full-stack applications efficiently.

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *