Setting up Next.js
First run the following command to initialize the next js project with supabase, typescript, and tailwind: npx create-next-app@latest
. Select all of the default options:
Setting up Prisma
Run the following command to install prisma:
npm install prisma --save-dev
Once prisma is installed run the following command to initialize the schema file and the .env file:
npx prisma init
There should now be a .env file. You should add your database_url to connect prisma to your database. You should also add your supabase url and your anon key for alter. Should look like this:
// .env
DATABASE_URL=url
NEXT_PUBLIC_SUPABASE_URL=url
NEXT_PUBLIC_SUPABASE_ANON_KEY=key
Inside your schema.prisma you should add your model, i am just using some random model for now:
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Post {
id String @default(cuid()) @id
title String
content String?
published Boolean @default(false)
author User? @relation(fields: [authorId], references: [id])
authorId String?
}
model User {
id String @default(cuid()) @id
name String?
email String? @unique
createdAt DateTime @default(now()) @map(name: "created_at")
updatedAt DateTime @updatedAt @map(name: "updated_at")
posts Post[]
@@map(name: "users")
}
Now you can run the following command to sync your database with your schema:
npx prisma db push
In order to access prisma on the client side you need to install prisma client. You can do so by running the following command:
npm install @prisma/client
Your client must be in sync with your schema as well and you can do this by running the following command:
npx prisma generate
When you run npx prisma db push
the generate command is automatically called.
In order to access the prisma client you need to create an instance of it, so create a new folder in the src directory called lib, and add a new file called prisma.ts to it.
// prisma.ts
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
export default prisma;
Now you can import the same instance of Prisma in any file.