Camkode
Camkode

Using Node.js with Prisma ORM for PostgreSQL

Posted by Kosal

Using Node.js with Prisma ORM for PostgreSQL

When working with PostgreSQL in Node.js, developers seek tools that simplify database access while providing type safety, performance, and a great developer experience. Prisma ORM is a modern solution that fits this need.

In this guide, you'll learn how to integrate Prisma with a Node.js application using PostgreSQL. This version includes a custom Prisma client output path and how to correctly import it.


What is Prisma?

Prisma is a next-generation ORM for Node.js and TypeScript. It offers:

  • Type-safe database queries
  • A clean data modeling syntax
  • Auto-generated query client
  • Easy schema migrations
  • Compatibility with PostgreSQL, MySQL, SQLite, SQL Server, and MongoDB

Prerequisites

  • Node.js (v18 or newer)
  • PostgreSQL database
  • npm (Node package manager)
  • Basic understanding of JavaScript

Step 1: Initialize Your Project

Create and initialize a new Node.js project:

mkdir prisma-postgres-app
cd prisma-postgres-app
npm init -y

Step 2: Install Prisma

Install Prisma CLI and Prisma client:

npm install prisma --save-dev
npm install @prisma/client

Then initialize Prisma:

npx prisma init

This creates the following:

  • .env file (for environment variables)
  • prisma/schema.prisma (for defining your data model)

Step 3: Configure PostgreSQL Connection

Open .env and set your database connection URL:

DATABASE_URL="postgresql://username:password@localhost:5432/mydatabase"

Replace the placeholder values with your actual database credentials.

Step 4: Define the Data Model

Edit prisma/schema.prisma to define your database schema. Here's an example User model:

generator client {
  provider = "prisma-client-js"
  output   = "./generated/prisma"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

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

⚠️ Note: The output line customizes where the Prisma Client will be generated.

Step 5: Apply the Schema to the Database

Run a migration to create the necessary tables:

npx prisma migrate dev --name init

Alternatively, if you want to push the schema without creating a migration:

npx prisma db push

Step 6: Generate Prisma Client

Generate the Prisma client based on your schema:

npx prisma generate

This will generate the client in the ./generated/prisma folder.

Step 7: Create and Run Your App

Create a file named index.js and write the following code:

const { PrismaClient } = require('./generated/prisma'); // <- Custom path
const prisma = new PrismaClient();

async function main() {
  // Create a user
  const user = await prisma.user.create({
    data: {
      name: 'Kosal',
      email: 'kosal@example.com',
    },
  });
  console.log('Created user:', user);

  // Read all users
  const users = await prisma.user.findMany();
  console.log('All users:', users);
}

main()
  .catch((e) => {
    console.error(e);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

Then run the app:

node index.js

Expected output:

Created user: {
  id: 3,
  name: 'Kosal',
  email: 'kosal@example.com',
  createdAt: 2025-05-19T03:00:21.773Z
}
All users: [
  {
    id: 3,
    name: 'Kosal',
    email: 'kosal@example.com',
    createdAt: 2025-05-19T03:00:21.773Z
  }
]

This confirms that your Prisma setup is working correctly with PostgreSQL and the Prisma Client was imported successfully.

Step 8: Use Prisma Studio (Optional)

To visually browse and edit your data, use Prisma Studio:

npx prisma studio

This opens a local web interface at http://localhost:5555.

Common Gotcha: Prisma Client Not Found

If you see an error like:

@prisma/client did not initialize yet. Please run "prisma generate"

Make sure you're importing the client from the correct path:

  • Default: require('@prisma/client')
  • Custom output: require('./generated/prisma')

Also, ensure you’ve run:

npx prisma generate

Conclusion

Prisma makes working with PostgreSQL in Node.js more efficient, type-safe, and enjoyable. With its powerful tools like schema modeling, code generation, and Prisma Studio, you can build robust applications quickly and confidently.

Whether you're building a small prototype or a full-scale production app, Prisma offers the right balance of flexibility and developer ergonomics.