DEV Community

Isaac Dyor
Isaac Dyor

Posted on

5 4 1 1 1

Building a next app with Prisma.

Create your next application

npx create-next-app@latest

Install Prisma

npm install prisma --save-dev

Initialize Prisma project

npx prisma init

Add your postgres link to your .env file. Make sure that everything is on the same line.

DATABASE_URL="postgresql:blahblahblah"

Create your database schema in the prisma.schema file

// schema.prisma
datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

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")
}
Enter fullscreen mode Exit fullscreen mode

Push the schema to your database

npx prisma db push

Install prisma client

`npm install @prisma/client'

Updata your prisma client

`npx prisma generate'

Create a new directory called lib and a prisma.js file in it.

In the prisma.js file you have to create an instance of the Prisma client.

Then you can import your instance of the Prisma client into any file you need. Then you create a getServerSideProps function to query the data. Then you can display those props however you want.

import prisma from '../lib/prisma';
import React from "react"

export const getServerSideProps = async () => {
  const feed = await prisma.post.findMany({
    where: { published: true },
    include: {
      author: {
        select: { name: true },
      },
    },
  });
  return { props: { feed } };
}


const Blog = ({feed}) => {
  console.log(feed)
  return (
    <div>
      {feed[0].title}
    </div>
  )
}

export default Blog
Enter fullscreen mode Exit fullscreen mode

My next post might be on creating a REST API with Prisma.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay