SB
Loading Light/Dark Toggle

1

1

Written by:

sarfraz alam

.

4 min read

Integration of prisma in nextjs.

in this blog, i will create a simple to do list project in o

in this blog, i will create a simple to do list project in order for to understand how to integrate prisma in your nextjs application so, without further ado, lets get started step 1: create a folder name NextApp in your destop and open it in visual studio code step 2: install nextjs package in NextApp folder npx install create-next-app@latest . if you are in NextApp folder make sure add . (dot) at the end. step 3: install prismaORM npm install -D prisma after installing, initialize prisma npx prisma init step 4: as soon as you run npx prisma init a prisma folder will be created in the root of your folder and inside prisma folder there will be a file name schema.prisma inside of the file set your database which you want to use, i will add postgresqsl, so add postrgesql in provider and created model something like this model User { id String @db @default(uuid) name String email String @unique postId String post Post[] } model Post { id String @db @default(uuid) content String userId String user User @relation(fields:[userId], refrence[id]) } step 5: after setting your database url and creating your model, go into the terminal and run npx prisma migrate dev — name init now you model have been created this is how you integrate prisma in nextjs application now, I am going to show you how you create intry in your database and how you can show that post in you web browser lets go 1 create post: first of all created separate new folder and inside of that created action.ts file, make sure add “use server” at top of the file import prisma from “prismaClient” export async const CreatePost = (body:string)=>{ awiat prisma.post.create{ data:{ content:body } now, call CreatPost function when you submit the post and pass the content 2 Get post: now you have created a post so lets fetch that post and show it in the application in action.ts expost async const FetchPost = () =>{ const post = await prisma.post.findMany({}) return post revalidatedPath(‘/’) } 3 Get post: show it in application, in order for you to shaw the post in web app const posts = awiat FetchPost() and map the post 3 update post: in action.ts export async const UpdatePost = (id:string,text:string) =>{ await prisma.post.update({ where:{ postId:id} data:{content:text} }) revalidatedPath(‘/’) } 3 detele post: export const DeletPost = (id:string)=>{ await prisma.post.delete{where:{id}} revalidatedPath(‘/’) } and call DeletePost at the delete button in client components and post id of the post you want to delete. that’s all for this blog and thank you so much for reading the blog