Prisma + Postgres
awalias

awalias @awalias

About: Co-Founder & CTO at Supabase | YC Alum

Location:
Singapore
Joined:
Apr 15, 2020

Prisma + Postgres

Publish Date: Oct 30 '24
524 48

In this tutorial, we'll explore how to set up Prisma + Postgres. We'll use real-world examples involving books and authors.

Prerequisites for Prisma + Postgres

Before we begin, ensure you have the following installed:

  • Node.js (v14 or later)
  • npm or yarn
  • An account on Supabase

Setting Up Prisma + Postgres

Supabase provides a hosted Postgres database for use with Prisma, making it easy to get started without setting up your own database server. Supabase is quick and easy to get started, and is a cost effective way to scale up to millions of users if your project gets traction.

  1. Create a New Supabase Project
    • Sign in to your Supabase account.
    • Click on "New Project".
    • Fill in the project details and click "Create new project".
  2. Retrieve Database Connection Details

    • In the navigation bar, go to "Project Settings" > "Database".
    • Copy the Connection string (URI) for Postgres. You’ll need it in the next step:

      postgres://postgres.[ref]:[password]@[region].pooler.supabase.com:6543/postgres
      

Setting Up Prisma in Your Project

Prisma is an ORM that simplifies database interactions in Node.js applications.

  1. Initialize a Node.js Project

    mkdir prisma-postgres
    cd prisma-postgres
    npm init -y
    
    
  2. Install Prisma and Postgres Client

    npm install prisma --save-dev
    npm install @prisma/client
    
    
  3. Initialize Prisma

    npx prisma init
    
    

    This command creates a prisma directory with a schema.prisma file and a .env file.

Configuring Prisma + Postgres

  1. Set Up the Database Connection

    • Open the .env file (located in the new prisma folder).
    • Add DATABASE_URL and DIRECT_URL you can get the connection details here:

      DATABASE_URL="postgres://postgres.[ref]:[password]@aws-0-[region].pooler.supabase.com:6543/postgres?pgbouncer=true"
      
      DIRECT_URL="postgres://postgres.[ref]:[password]@aws-0-[region].pooler.supabase.com:5432/postgres"
      
      

The direct connection (on port 5432 is required for running database migrations against the database).

  1. Define the Data Model

    • Open prisma/schema.prisma.
    • Update the datasource block to include DIRECT_URL like so:

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

    Add your data models. For a library system:

    ```
    model Author {
      id     Int     @id @default(autoincrement())
      name   String
      books  Book[]
    }
    
    model Book {
      id        Int      @id @default(autoincrement())
      title     String
      author    Author   @relation(fields: [authorId], references: [id])
      authorId  Int
    }
    
    ```
    

Generating the Postgres Schema

Use Prisma Migrate to apply your schema to the Postgres database on Supabase.

npx prisma migrate dev --name init

Enter fullscreen mode Exit fullscreen mode

This command will:

  • Generate migration files.
  • Apply the migration to the Postgres database.
  • Generate the Prisma Client.

Using Prisma Client to Interact with Prisma + Postgres

Create a script.js file to test database operations.

const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function main() {
  // Create a new author
  const author = await prisma.author.create({
    data: {
      name: 'Yevgeny Zamyatin',
    },
  });

  // Create a new book
  const book = await prisma.book.create({
    data: {
      title: 'We',
      authorId: author.id,
    },
  });

  // Retrieve all books with their authors
  const books = await prisma.book.findMany({
    include: { author: true },
  });

  console.log(books);
}

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

Enter fullscreen mode Exit fullscreen mode

Run the script:

node script.js

Enter fullscreen mode Exit fullscreen mode

You should see an array of books with their associated authors logged to the console.

Conclusion

Congratulations! You've set up Prisma with Postgres. This setup allows you to interact with your Postgres database seamlessly using Prisma.


By following this guide, you've taken the first steps toward building robust applications with Prisma and Postgres.

Comments 48 total

  • awalias
    awaliasOct 30, 2024

    If anyone needs help regarding Prisma / Postgres you can get support in our discord

    • Steve_Val
      Steve_ValOct 30, 2024

      The memes in there are crazy lol

      Also note for anyone else who's wondering the official Prisma documentation related to this is here: prisma.io/docs/orm/overview/databa...

      The important step adding

      datasource db {
        provider  = "postgresql"
        url       = env("DATABASE_URL")
        directUrl = env("DIRECT_URL")
      }
      
      Enter fullscreen mode Exit fullscreen mode

      Very nice.

      • swamp_dog
        swamp_dogOct 30, 2024

        I was trying initially without the direct_url but apparently it's required if you need to do migrations.

    • Joshen Lim
      Joshen LimOct 30, 2024

      Hopefully this might be helpful - there's a set of handy instructions on your projects' home page if you click the "Connect" button and select the "ORMs" tab
      Image description

    • Supabase Community
      Supabase CommunityOct 30, 2024

      Prisma Postgres is an incredible pairing for a backend. Both tools are used and loved by the Supabase Community.

    • Lee AVULAT
      Lee AVULATOct 30, 2024

      Nice guide. I would add that if you want to use prisma to generate migrations. For those to be usable with supabase-js and postgrest I recommend to leverage the native database functions in your "id" definitions like mentioned here: github.com/supabase/cli/issues/277...

    • Thor 雷神
      Thor 雷神Oct 30, 2024

      You can also find some details on using Row Level Security (RLS) with Prisma here: supabase.com/partners/integrations...

      • Jon
        JonNov 1, 2024

        This is an absolute game changer!

    • Joel Lee
      Joel LeeOct 31, 2024

      Thanks, will check it out

    • Julien Goux
      Julien GouxOct 31, 2024

      Prisma and Supabase are really a great fit. Great combo!

    • SupaDavid
      SupaDavidOct 31, 2024

      awesome

    • David Wilson
      David WilsonOct 31, 2024

      yes yes yes

    • Deji Ibrahim
      Deji IbrahimOct 31, 2024

      Easy to setup 👌, thanks!

    • Chase Granberry
      Chase GranberryOct 31, 2024

      💚 Prisma + Supabase

    • Karlo Ison
      Karlo IsonOct 31, 2024

      Awesome! 🤩

    • Tyler Hillery
      Tyler HilleryOct 31, 2024

      Prisma + Supabse is an awesome combo.

    • Tyler Hillery
      Tyler HilleryOct 31, 2024

      The discord is very welcoming to new comers!

    • Greg Richardson
      Greg RichardsonOct 31, 2024

      Super seamless, nice 😃🚀

    • Jessica Shears
      Jessica ShearsOct 31, 2024

      This is awesome!

    • Jon
      JonNov 1, 2024

      This is so sick! 💯

    • Tyler Shukert
      Tyler ShukertNov 1, 2024

      I know a lot of apps built with this combination!

    • Francesco Sansalvadore
      Francesco SansalvadoreNov 1, 2024

      Prisma + Supabase is the perfect combo.

    • flutter_for_life
      flutter_for_lifeNov 1, 2024

      Nice share!

    • Crispy1975
      Crispy1975Nov 1, 2024

      Supabase and Prisma is the perfect match for us, it makes life so easy to build things quickly.

    • Chandana Anumula
      Chandana AnumulaNov 2, 2024

      This is great!!

    • abc3 🇺🇦
      abc3 🇺🇦Nov 2, 2024

      Supabase and Prisma makes development so much easier. Love this combo

    • Alexander Korotkov
      Alexander KorotkovNov 2, 2024

      Brilliant, thank you!

    • Alexander Korotkov
      Alexander KorotkovNov 2, 2024

      Thank you!

    • Raminder Singh
      Raminder SinghNov 3, 2024

      I was just trying out setting up Prisma with Postgres and found this guide. Thanks for writing this.

    • Raminder Singh Sidhu
      Raminder Singh SidhuNov 3, 2024

      Thank you so much, this is what I was looking for. A great guide to setup Prisma with Postgres.

    • Illia Basalaiev
      Illia BasalaievNov 3, 2024

      This is amazing! 💪💪

    • samrose
      samroseNov 3, 2024

      Thank you so much. I wish I had known how easy this was in the past. Grateful for this resource!

    • Sreyas Udayavarman
      Sreyas UdayavarmanNov 4, 2024

      Thankyou!

    • Guilherme Souza
      Guilherme SouzaNov 4, 2024

      That is awesome!

    • Kamil Ogórek
      Kamil OgórekNov 5, 2024

      Always happy to help

  • Chris
    ChrisOct 30, 2024

    thanks for this! If I am using a pooler like Supavisor does that mean I do not use Accelerate or anything, just the Prisma library and Supabase handles the rest?

  • Aleksi Immonen
    Aleksi ImmonenOct 30, 2024

    Excellent guide !

  • Aleksi Immonen
    Aleksi ImmonenOct 30, 2024

    Excellent guide!

  • Dave
    DaveOct 31, 2024

    This is great!

  • timnpalmer
    timnpalmerOct 31, 2024

    Super valuable guide, thanks

  • Wen Bo Xie
    Wen Bo XieOct 31, 2024

    Excited to use Prisma and Supabase together! This makes it so easy to get started and distinguish between which database connection strings to use and why.

  • Jon
    JonNov 1, 2024

    What an incredibly powerful stack! Prisma and Postgres powered by Supabase! 🚀

  • Sreyas Udayavarman
    Sreyas UdayavarmanNov 4, 2024

    This is great! Easy to setup.

  • Qian Li
    Qian LiNov 5, 2024

    Thanks for the starter tutorial -- it's clear and simple. Things can get tricker if you modify the schema and want to actually push to production:

    • prisma migrate dev is only for dev environment. Use npx prisma migrate deploy for production and testing (CI/CD pipelines). Docs
    • Run npx prisma generate to generate new client code whenever you modify the schema as well.

    Also, I noticed that Prisma doesn't really support rolling back schema changes. So to revert changes you need to revert your schema file and generate a "new" migration/client to undo the previous change instead.

  • Subham
    Subham Nov 6, 2024

    Interesting guide, but honestly, why go through all this setup with Prisma + Postgres when you could use Drizzle ORM? Drizzle is so much cleaner and more TypeScript friendly without all the heavy migration overhead.

Add comment