Before we install Prisma in Express.js. Let's explain what Express.js and Prisma are.
Express is a popular, free, open-source, and minimalist web application framework for Node.js. Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
Prisma is a modern, open-source database toolkit for Node.js and TypeScript that simplifies database interactions by providing a type-safe, object-oriented API, replacing raw SQL with intuitive code for tasks like CRUD operations. It features a powerful ORM (Object-Relational Mapper) for easy data modeling, a migration system (Prisma Migrate), and a GUI for database inspection (Prisma Studio). It supports various databases (PostgreSQL, MySQL, MongoDB, etc.) and ensures type safety, catching errors at compile time, making development faster and more reliable
Prerequisites for Installing Prisma ORM
- Node.js (version 16.13.0 or higher)
- npm or yarn package manager
- A basic Express.js application setup
- A database (PostgreSQL, MySQL, SQLite, MongoDB, or SQL Server)
Step 1: Set Up Your Express.js Project
If you haven't created an Express.js project yet, initialize one with these commands:
mkdir express-prisma-app
cd express-prisma-app
npm init -y
npm install express
Create a basic Express server in index.js:
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json());
app.get('/', (req, res) => {
res.json({ message: 'Express server with Prisma ORM' });
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Step 2: Install Prisma ORM Dependencies
Install Prisma CLI as a development dependency and Prisma Client as a regular dependency:
npm install prisma --save-dev
npm install @prisma/client
For TypeScript projects, also install type definitions:
npm install typescript ts-node @types/node @types/express --save-dev
Step 3: Initialize Prisma in Your Express Application
Run the Prisma initialization command to create the necessary configuration files:
npx prisma init
This command creates:
- A prisma directory with a schema.prisma file
- A .env file for your database connection string
Step 4: Configure Your Database Connection
Open the .env file and add your database connection URL. Here are examples for different databases:
PostgreSQL:
DATABASE_URL="postgresql://username:password@localhost:5432/mydb?schema=public"
MySQL:
DATABASE_URL="mysql://username:password@localhost:3306/mydb"
SQLite:
DATABASE_URL="file:./dev.db"
MongoDB:
DATABASE_URL="mongodb+srv://username:password@cluster.mongodb.net/mydb"
Step 5: Define Your Prisma Schema
Edit the prisma/schema.prisma file to define your database models. Here's an example schema:
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql" // Change to your database
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
createdAt DateTime @default(now())
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
createdAt DateTime @default(now())
}
Step 6: Run Prisma Migrations
Create and apply your database migrations:
npx prisma migrate dev --name init
This command:
- Creates SQL migration files
- Applies migrations to your database
- Generates the Prisma Client
Step 7: Generate Prisma Client
If you need to regenerate the Prisma Client after schema changes:
npx prisma generate
Step 8: Integrate Prisma Client with Express.js
Create a prisma.js file to instantiate the Prisma Client:
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
module.exports = prisma;
Step 9: Use Prisma in Express Routes
Update your Express application to use Prisma for database operations:
const express = require('express');
const prisma = require('./prisma');
const app = express();
app.use(express.json());
// Create a new user
app.post('/users', async (req, res) => {
try {
const { email, name } = req.body;
const user = await prisma.user.create({
data: { email, name }
});
res.json(user);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Get all users
app.get('/users', async (req, res) => {
try {
const users = await prisma.user.findMany({
include: { posts: true }
});
res.json(users);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Get user by ID
app.get('/users/:id', async (req, res) => {
try {
const { id } = req.params;
const user = await prisma.user.findUnique({
where: { id: Number(id) },
include: { posts: true }
});
res.json(user);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Express server with Prisma running on port ${PORT}`);
});
Prisma Studio is a visual database GUI (Graphical User Interface) included with Prisma, allowing developers to easily explore, view, and edit data in their databases directly in a web browser through a user-friendly interface, supporting CRUD operations, filtering, sorting, and visualizing data relationships, accessible locally via
npx prisma studio
Conclusion
Installing Prisma ORM in Express.js enhances your Node.js application with type-safe database queries, automatic migrations, and excellent developer experience. By following this guide, you've successfully integrated Prisma with Express.js and learned how to perform CRUD operations efficiently
Top comments (0)