Leon

How to setup a Next.js project with Prisma and Supabase

Topics
NextjsSupabasePrisma
Published on 
20 Jan 2025

This is a step-by-step guide to connecting Supabase and Prisma in a Next.js project:

1. Create Supabase Project

  1. Go to supabase.comNew Project. (copy the database password for .env)
  2. Then you can click the connection button and see the connection information on ORMs section.
Create new project in Supabase

If you are not using the generated password, make sure not to use special characters in it as it might prevent you from connecting successfully to Supabase.

Project's connect button

Click the connect button and go to the ORMs section.

Connection information

Configure Environment Variables

Create/update .env:

(Don't forget to add `.env` in gitignore to not commit any private information.)

.env
1DB_PASSWORD="gUNRwPpMp2oUzC9R"
2
3DATABASE_URL="postgresql://postgres.kuclwggtedhdocddelff:gUNRwPpMp2oUzC9R@aws-0-ap-southeast-1.pooler.supabase.com:6543/postgres?pgbouncer=true"
4
5DIRECT_URL="postgresql://postgres.kuclwggtedhdocddelff:gUNRwPpMp2oUzC9R@aws-0-ap-southeast-1.pooler.supabase.com:5432/postgres"

2. Install Prisma

1npm install prisma @prisma/client --save-dev
2npx prisma init

3. Configure Prisma Schema

Update prisma/schema.prisma:

1generator client {
2  provider = "prisma-client-js"
3  output   = "../app/generated/prisma"
4}
5
6datasource db {
7  provider = "postgresql"
8  url      = env("DATABASE_URL")
9  directUrl = env("DIRECT_URL")
10}
11
12// Define models matching your Supabase tables
13model User {
14  id        String   @id @default(cuid())
15  email     String   @unique
16  name      String?
17  createdAt DateTime @default(now()) @map("created_at")
18  @@map("users")
19}

4. Setup Prisma Instance

Create utils/db.ts

Add below code to avoid multiple Prisma client instances.

ref: https://www.prisma.io/docs/orm/more/help-and-troubleshooting/nextjs-help

db.ts
1import { PrismaClient } from '@prisma/client';
2
3const prismaClientSingleton = () => {
4  return new PrismaClient();
5};
6
7type PrismaClientSingleton = ReturnType<typeof prismaClientSingleton>;
8
9const globalForPrisma = globalThis as unknown as {
10  prisma: PrismaClientSingleton | undefined;
11};
12
13const prisma = globalForPrisma.prisma ?? prismaClientSingleton();
14
15export default prisma;
16
17if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;

5. Connect Prisma and Supabase

Option 1: Pull Existing Supabase Schema

1npx prisma db pull

Option 2: Push New Schema to Supabase

1npx prisma db push

Terminal information

To have a visual, web-based editor for managing and exploring the data in your database when using Prisma ORM. You can run below command to launch the Prisma Studio.

1npx prisma studio
Prisma Studio