Prisma Postgres
Prisma Postgres is a managed PostgreSQL database that scales to zero and works with Prisma ORM and Prisma Studio. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to Prisma Postgres using Prisma ORM, and generate a Prisma Client for type-safe access to your database.
- Node.js v20.19 or later
- No database needed: you create a Prisma Postgres database with one command in step 4
mkdir hello-prisma
cd hello-prismaInitialize a TypeScript project:
bun init
bun add typescript tsx @types/node --dev
bunx tsc --initpnpm init
pnpm add typescript tsx @types/node --save-dev
pnpm tsc --inityarn init
yarn add typescript tsx @types/node --dev
yarn tsc --initnpm init
npm install typescript tsx @types/node --save-dev
npx tsc --initInstall the packages needed for this quickstart:
bun add prisma@prev @types/pg --dev
bun add @prisma/client@7 @prisma/adapter-pg pg dotenvpnpm add prisma@prev @types/pg --save-dev
pnpm add @prisma/client@7 @prisma/adapter-pg pg dotenvyarn add prisma@prev @types/pg --dev
yarn add @prisma/client@7 @prisma/adapter-pg pg dotenvnpm install prisma@prev @types/pg --save-dev
npm install @prisma/client@7 @prisma/adapter-pg pg dotenvHere's what each package does:
prisma- The Prisma CLI for running commands likeprisma init,prisma migrate, andprisma generate@prisma/client- The Prisma Client library for querying your database@prisma/adapter-pg- Thenode-postgresdriver adapter that connects Prisma Client to your databasepg- The node-postgres database driver@types/pg- TypeScript type definitions for node-postgresdotenv- Loads environment variables from your.envfile
Update tsconfig.json for ESM compatibility:
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "bundler",
"target": "ES2023",
"strict": true,
"esModuleInterop": true,
"ignoreDeprecations": "6.0"
}
}Update package.json to enable ESM:
{
"type": "module"
}You can now run Prisma CLI commands using your package manager:
bunx prismapnpm prismayarn prismanpx prismaNext, set up your Prisma ORM project by creating your Prisma Schema file with the following command:
Next, set up your Prisma ORM project by creating your Prisma Schema file with the following command:
bunx --bun prisma init --output ../generated/prismapnpm prisma init --output ../generated/prismayarn prisma init --output ../generated/prismanpx prisma init --output ../generated/prismaprisma init creates the Prisma scaffolding and a local DATABASE_URL.
This command does a few things:
- Creates a
prisma/directory with aschema.prismafile containing your database connection and schema models - Creates a
.envfile in the root directory for environment variables - Creates a
prisma7.config.tsfile for Prisma configuration
The generated prisma7.config.ts file looks like this:
// This file was generated by Prisma, and assumes you have installed the following:
// npm install --save-dev prisma dotenv
import "dotenv/config";
import { defineConfig } from "prisma/config";
export default defineConfig({
schema: "prisma/schema.prisma",
migrations: {
path: "prisma/migrations",
},
datasource: {
url: process.env["DATABASE_URL"],
},
});The generated schema uses the ESM-first prisma-client generator with a custom output path:
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}
datasource db {
provider = "postgresql"
}Create a Prisma Postgres database and replace the generated DATABASE_URL in your .env file with the postgres://... connection string from the CLI output:
bunx create-db@latestpnpm dlx create-db@latestyarn dlx create-db@latestnpx create-db@latestOpen prisma/schema.prisma and add the following models:
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}
datasource db {
provider = "postgresql"
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
} Create your first migration to set up the database tables:
bunx prisma migrate dev --name initpnpm prisma migrate dev --name inityarn prisma migrate dev --name initnpx prisma migrate dev --name initThis command creates the database tables based on your schema.
Now run the following command to generate the Prisma Client:
bunx prisma generatepnpm prisma generateyarn prisma generatenpx prisma generateNow that you have all the dependencies installed, you can instantiate Prisma Client. You need to pass an instance of the Prisma ORM driver adapter to the PrismaClient constructor:
import "dotenv/config";
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "../generated/prisma/client";
const connectionString = `${process.env.DATABASE_URL}`;
const adapter = new PrismaPg({ connectionString });
const prisma = new PrismaClient({ adapter });
export { prisma };Create a script.ts file to test your setup:
import { prisma } from "./lib/prisma";
async function main() {
// Create a new user with a post
const user = await prisma.user.create({
data: {
name: "Alice",
email: "alice@prisma.io",
posts: {
create: {
title: "Hello World",
content: "This is my first post!",
published: true,
},
},
},
include: {
posts: true,
},
});
console.log("Created user:", user);
// Fetch all users with their posts
const allUsers = await prisma.user.findMany({
include: {
posts: true,
},
});
console.log("All users:", JSON.stringify(allUsers, null, 2));
}
main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});Run the script:
bunx tsx script.tspnpm dlx tsx script.tsyarn dlx tsx script.tsnpx tsx script.tsYou should see the created user and all users printed to the console.
Prisma Studio is a visual editor for your database. Launch it with:
npx prisma studioPrisma ORM is set up. These are the pages you are most likely to need next:
- Learn more about Prisma Client: Explore the Prisma Client API for advanced querying, filtering, and relations
- Database migrations: Learn about Prisma Migrate for evolving your database schema
- Performance optimization: Discover query optimization techniques
- Build a full application: Check out our framework guides to integrate Prisma ORM with Next.js, Express, and more
- Join the community: Connect with other developers on Discord