
If you're building backend applications with Node.js, you know that working with databases is a big part of the job. Whether you're creating a user authentication system, an e-commerce application, or a REST API, you need a reliable way to store, retrieve, update, and delete data.
Traditionally, developers write SQL queries directly or use libraries to interact with databases. These approaches work well, but as an application grows, managing queries, relationships, and database changes can become more complicated.
This is where Prisma ORM comes in.
Prisma ORM is a modern database toolkit for Node.js and TypeScript that provides type-safe database queries, schema management, and migration tools.
In this guide, we'll install Prisma from scratch, connect it to PostgreSQL, create our first model, generate Prisma Client, and perform basic database operations.
By the end, you'll have a working Prisma setup that you can use as the foundation for your own Node.js backend projects.
What Is Prisma ORM?
Prisma is an ORM, which stands for Object-Relational Mapping. It helps developers interact with databases using application code instead of manually writing SQL queries for every operation.
For example, suppose you want to retrieve a user from a database.
Using SQL, you might write:
SELECT * FROM "User" WHERE id = 1;Using Prisma Client, you can write:
const user = await prisma.user.findUnique({
where: {
id: 1,
},
});Both approaches can retrieve the same record. Prisma adds a structured query API and generates TypeScript types based on your schema.
Prisma ORM consists of several important tools:
Prisma Client: A generated client for querying your database.
Prisma Schema: A place to define your data models, fields, and relationships.
Prisma Migrate: A migration system for tracking and applying schema changes to supported relational databases.
Prisma Studio: A visual interface for viewing and editing database records.
Prisma supports several databases, including PostgreSQL, MySQL, SQLite, MongoDB, and others, although available features depend on the database provider.
Prerequisites Before Installing Prisma
Before starting, make sure you have the following:
Node.js: Installed on your computer.
npm: Included with Node.js.
TypeScript: We'll use it for this tutorial.
PostgreSQL: A local or hosted database.
A code editor: VS Code or another editor of your choice.
You can check whether Node.js and npm are installed by running:
node -v
npm -vIf both commands return version numbers, you're ready to continue.
You should also have access to a PostgreSQL database and know its connection details.
If you don't already have PostgreSQL installed, you can use a hosted PostgreSQL service instead of setting up a local database.
Step 1: Create a Node.js Project
First, create a new folder for your project.
Open your terminal and run:
mkdir prisma-setup
cd prisma-setup
npm init -yThis creates a new Node.js project with a package.json file.
Next, install TypeScript and the development tools:
npm install -D typescript tsx @types/nodeInitialize TypeScript:
npx tsc --initWe'll use TypeScript because Prisma provides generated types and autocomplete that make database queries easier to write and maintain.
Step 2: Install Prisma ORM
Now let's install Prisma and its required packages.
For this tutorial, we're using Prisma 7 with PostgreSQL.
Run:
npm install @prisma/client @prisma/adapter-pg pg dotenv
npm install -D prismaHere's what each package does:
Package | Purpose |
|---|---|
| Provides the Prisma CLI for initialization, migrations, and other commands. |
| Provides the runtime database client. |
| Connects Prisma Client to PostgreSQL through a driver adapter. |
| Provides the PostgreSQL driver. |
| Loads environment variables from your |
| Allows you to write TypeScript code. |
| Runs TypeScript files during development. |
One important detail: Prisma 7 uses database driver adapters for this setup. If you've followed an older Prisma tutorial, you might see a different installation process.
Step 3: Initialize Prisma
After installing the dependencies, initialize Prisma for PostgreSQL.
Run:
npx prisma init --datasource-provider postgresqlThis command creates the initial Prisma configuration and schema files.
Your project structure will look similar to this:
prisma-setup/
├── prisma/
│ └── schema.prisma
├── prisma.config.ts
├── node_modules/
├── package.json
├── tsconfig.json
└── .envThe exact files can vary slightly depending on your Prisma version and initialization options.
Let's understand the two most important files.
schema.prisma defines your database models and relationships.
prisma.config.ts contains Prisma configuration, including the schema location, migration directory, and database connection URL.
Keeping these responsibilities separate makes it easier to organize your project.
Step 4: Configure the Database Connection
Open your .env file and add your PostgreSQL connection string.
DATABASE_URL="postgresql://postgres:your_password@localhost:5432/prisma_setup"Replace the following values with your actual database details:
postgres: Your database username.your_password: Your database password.localhost: Your database host.5432: The default PostgreSQL port.prisma_setup: Your database name.
Make sure the database exists before continuing.
For example, if you're using PostgreSQL locally, you can create a database named prisma_setup through your preferred PostgreSQL administration tool.
Security tip: Never commit real database credentials to GitHub. Add .env to your .gitignore file and use environment variables or a secrets manager in production.
Configure prisma.config.ts
Open prisma.config.ts and configure it as follows:
import "dotenv/config";
import { defineConfig, env } from "prisma/config";
export default defineConfig({
schema: "prisma/schema.prisma",
migrations: {
path: "prisma/migrations",
},
datasource: {
url: env("DATABASE_URL"),
},
});This tells Prisma where to find your schema, where to store migration files, and which database connection string to use.
If your project uses a version-specific configuration filename generated by the Prisma CLI, keep the filename created by that version.
Step 5: Configure Your Prisma Schema
Now open prisma/schema.prisma.
Replace its contents with the following:
generator client {
provider = "prisma-client"
output = "../src/generated/prisma"
}
datasource db {
provider = "postgresql"
}
model User {
id Int @id @default(autoincrement())
name String
email String @unique
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}Let's understand each part.
1. The Generator
generator client {
provider = "prisma-client"
output = "../src/generated/prisma"
}This configuration tells Prisma to generate the client code inside src/generated/prisma.
The generated client provides the methods and TypeScript types that your application uses to query the database.
2. The Datasource
datasource db {
provider = "postgresql"
}This identifies PostgreSQL as the database provider.
In this Prisma 7 setup, the connection URL is configured in prisma.config.ts.
3. The User Model
model User {
id Int @id @default(autoincrement())
name String
email String @unique
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}This model describes the structure of your user records.
Here's what the fields mean:
id: The primary key for each user.@id: Marks a field as the primary key.@default(autoincrement()): Automatically generates an integer ID.name: Stores the user's name.email: Stores the user's email address.@unique: Prevents duplicate email values.createdAt: Stores when the record was created.@default(now()): Sets the creation timestamp.updatedAt: Tracks the last update made through Prisma.@updatedAt: Automatically updates the timestamp when Prisma updates the record.
You can add more fields as your application requirements grow.
Step 6: Create the Database Tables
Defining a model in schema.prisma doesn't automatically create a table in PostgreSQL.
You need to apply the schema to your database.
For a new development database, run:
npx prisma migrate dev --name initThis command creates a migration and applies it to the database.
Prisma also creates migration files that record the database changes.
Your project will now include a migration directory:
prisma/
├── migrations/
│ └── <timestamp>_init/
│ └── migration.sql
└── schema.prismaThe SQL migration describes the changes needed to create your database table.
This is useful when working with other developers because migration files can be committed to Git and applied consistently across environments.
Important: Use development migration commands only in appropriate development environments. For production deployments, apply committed migrations through your deployment process.
Step 7: Generate Prisma Client
Prisma Client provides the methods you use to interact with your database.
Generate it by running:
npx prisma generatePrisma reads your schema and generates the client code.
Because we configured the output directory as src/generated/prisma, the generated files will be placed there.
Your project structure will now look similar to this:
prisma-setup/
├── prisma/
│ ├── migrations/
│ └── schema.prisma
├── src/
│ └── generated/
│ └── prisma/
├── prisma.config.ts
├── package.json
└── .envThe generated directory should generally be treated as build output rather than a place to write application code manually.
Whenever you change your schema, regenerate Prisma Client if the change affects the generated client.
Step 8: Create a Reusable Prisma Client
In a real Node.js application, you usually want to initialize Prisma Client in one place and reuse it throughout your project.
This is similar to creating a database connection module when working with Mongoose, Sequelize, or another database library.
Create a file named src/lib/prisma.ts.
import "dotenv/config";
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "../generated/prisma/client";
const connectionString = process.env.DATABASE_URL;
if (!connectionString) {
throw new Error("DATABASE_URL is not configured");
}
const adapter = new PrismaPg({
connectionString,
});
const prisma = new PrismaClient({
adapter,
});
export default prisma;Let's break this down.
Import Prisma Client
import { PrismaClient } from "../generated/prisma/client";This imports the client generated from your schema.
Create the PostgreSQL adapter
const adapter = new PrismaPg({
connectionString,
});The adapter connects Prisma Client to PostgreSQL using the pg driver.
Initialize Prisma Client
const prisma = new PrismaClient({
adapter,
});This creates the client instance that your application can use for database operations.
Export the instance
export default prisma;Now other files can import the same client instead of duplicating the initialization code.
For applications that use hot reload during development, consider caching the client instance on globalThis if repeated module initialization creates too many database connections.
Step 9: Create Your First User
Now let's test whether Prisma is working correctly.
Create a file named src/index.ts.
import prisma from "./lib/prisma";
async function main() {
const user = await prisma.user.create({
data: {
name: "Manjeet Kumar",
email: "manjeet@example.com",
},
});
console.log("User created successfully:");
console.log(user);
}
main()
.catch((error) => {
console.error("Database operation failed:", error);
process.exitCode = 1;
})
.finally(async () => {
await prisma.$disconnect();
});This code creates a new user in the database.
The prisma.user.create() method inserts the record and returns the created user.
Run the file:
npx tsx src/index.tsIf your database connection and schema are configured correctly, you'll see a response similar to this:
User created successfully:
{
id: 1,
name: 'Manjeet Kumar',
email: 'manjeet@example.com',
createdAt: ...,
updatedAt: ...
}The exact ID and timestamps will depend on your database.
If you see this output, congratulations! Your Prisma setup is working.
Step 10: Perform Basic CRUD Operations
Once Prisma is connected, you can perform CRUD operations.
CRUD stands for Create, Read, Update, and Delete.
Let's look at a few examples.
Create a User
const user = await prisma.user.create({
data: {
name: "Rahul",
email: "rahul@example.com",
},
});This creates a new user.
Remember that the email field is unique. If the email already exists, the database will reject the duplicate record.
Retrieve All Users
const users = await prisma.user.findMany();
console.log(users);The findMany() method retrieves matching records.
You can also sort the results:
const users = await prisma.user.findMany({
orderBy: {
createdAt: "desc",
},
});This returns the newest users first.
Find a User by Email
const user = await prisma.user.findUnique({
where: {
email: "manjeet@example.com",
},
});
console.log(user);Because email is unique, it can be used to retrieve a single matching user.
If no matching record exists, findUnique() returns null.
Update a User
const updatedUser = await prisma.user.update({
where: {
email: "manjeet@example.com",
},
data: {
name: "Manjeet Choudhary",
},
});This updates the user's name.
The where field identifies the record, while data contains the fields you want to change.
Delete a User
const deletedUser = await prisma.user.delete({
where: {
email: "manjeet@example.com",
},
});This removes the matching user from the database.
In a real application, make sure the request is authorized before deleting records.
Step 11: View Your Database With Prisma Studio
Prisma includes a visual database tool called Prisma Studio.
It allows you to browse your tables and inspect records without writing a query manually.
To start Prisma Studio, run:
npx prisma studioOpen the local address displayed in your terminal.
You should be able to view the User model and the records created in the previous steps.
Prisma Studio is especially helpful when debugging an API or checking whether your database operations are working as expected.
Step 12: Add Useful Scripts to package.json
You can simplify common commands by adding scripts to your package.json.
For example:
{
"scripts": {
"dev": "tsx watch src/index.ts",
"db:migrate": "prisma migrate dev",
"db:generate": "prisma generate",
"db:studio": "prisma studio"
}
}Keep your existing dependencies and other package settings when adding these scripts.
Now you can start your application with:
npm run devGenerate Prisma Client with:
npm run db:generateStart Prisma Studio with:
npm run db:studioFor database migrations, you can run:
npm run db:migrate -- --name add_user_fieldsUse a descriptive migration name whenever you make a meaningful schema change.
Common Prisma Installation Errors and How to Fix Them
Even a straightforward setup can run into problems. Here are a few common issues and their solutions.
1. Database Connection Error
You might see an error indicating that Prisma cannot connect to PostgreSQL.
Check the following:
Is PostgreSQL running?
Does the database exist?
Is the username correct?
Is the password correct?
Is the port correct?
Is
DATABASE_URLconfigured correctly?
If you're using a hosted database, also verify the provider's connection requirements.
2. Prisma Client Has Not Been Generated
If Prisma Client cannot be imported or the generated files are missing, run:
npx prisma generateAlso verify that the generator's output path matches the import path in your application.
3. Environment Variable Is Missing
If you see an error about DATABASE_URL, make sure the .env file exists in your project root.
Check that the variable name is spelled correctly and that the application loads environment variables before accessing them.
4. Duplicate Email Error
If you attempt to create two users with the same email, the unique constraint will prevent the operation.
Use a different email address or handle the unique-constraint error in your application.
5. Schema and Database Are Out of Sync
If you change your schema but don't apply the corresponding database changes, queries may fail.
For a relational database during development, create and apply a migration:
npx prisma migrate dev --name describe_your_changeThen regenerate the client if necessary:
npx prisma generateReview migration changes before applying them, especially if the database contains important data.
6. Prisma Version Differences
Many older tutorials use a different generator configuration and initialize Prisma Client without a driver adapter.
Prisma 7 introduced important configuration and connection changes, so older examples may not work without modification.
Always check that the commands and code match the Prisma version installed in your project.
Prisma ORM Best Practices for Beginners
As you start using Prisma in real applications, keep these practices in mind:
Use a separate Prisma module. Keep database initialization outside route handlers.
Use environment variables. Never hardcode production database credentials.
Validate incoming data. Generated TypeScript types do not replace runtime validation of API requests.
Use migrations. Track database schema changes and apply them consistently.
Handle database errors. Account for missing records, unique constraints, and connection failures.
Avoid unnecessary queries. Retrieve only the data your application needs.
Use transactions when appropriate. Keep related database operations consistent.
Manage database connections carefully. Avoid creating a new client for every request.
Keep generated code in sync. Regenerate Prisma Client after relevant schema changes.
Learn SQL fundamentals. Understanding indexes, relationships, and query performance will help you make better use of an ORM.
Frequently Asked Questions
1. Is Prisma ORM free to use?
Prisma ORM is an open-source project. Some related hosted services may have separate pricing, depending on the service and usage.
2. Can I use Prisma with JavaScript?
Yes. Prisma Client can be used in JavaScript applications. TypeScript is particularly useful because Prisma generates types that improve autocomplete and compile-time checking.
3. Which databases does Prisma support?
Prisma supports multiple databases, including PostgreSQL, MySQL, SQLite, MongoDB, SQL Server, and CockroachDB. Supported features vary by database provider and Prisma version.
4. What is the difference between Prisma and Prisma Client?
Prisma ORM is the broader database toolkit. Prisma Client is the generated query client used by your application to interact with the database.
5. Do I need to write SQL when using Prisma?
You can perform many database operations through Prisma Client without writing SQL directly. However, SQL knowledge is still valuable for understanding performance, debugging queries, and handling specialized database operations.
6. What is the purpose of schema.prisma?
The Prisma schema defines your data models, fields, relationships, and generator configuration. Prisma uses it to generate client code and support database schema management.
7. What is Prisma Migrate?
Prisma Migrate is a tool for managing database schema changes in supported relational databases. It creates migration files that can be tracked in version control and applied to different environments.
8. Can I use Prisma with Express.js?
Yes. Prisma works with Express.js and other Node.js frameworks. You can import Prisma Client into controllers, services, or repository modules to perform database operations.
9. Is Prisma better than Mongoose?
Neither tool is automatically better for every project. Prisma supports multiple database systems and provides a generated query API, while Mongoose focuses on MongoDB document modeling. Your database and application requirements should guide the decision.
10. Should I learn Prisma before SQL?
You can learn Prisma as a beginner, but understanding basic SQL concepts will help you design better schemas, debug issues, and optimize queries.
Conclusion
Prisma ORM makes database access more structured and provides a strong developer experience for Node.js and TypeScript applications.
In this guide, we installed Prisma, configured PostgreSQL, defined a model, applied a migration, generated Prisma Client, and performed basic CRUD operations.
We also explored Prisma Studio, common installation errors, and best practices for maintaining a reliable database layer.
The best way to become comfortable with Prisma is to use it in a small project. Start with a user model, add CRUD operations, and then introduce relationships, authentication, and pagination.
Once you understand the basics, you can use the same concepts to build larger applications with Express.js, NestJS, or Next.js.
Start small, understand how your schema maps to the database, and build from there.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


