DEV Community

Cover image for Adding Prisma to a Next.js project
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

Adding Prisma to a Next.js project

Prisma is a very cool ORM that we can use to access a database in JavaScript projects.
Prisma works with SDL (Schema Definition Language) to make writing migrations and type-safe code a breeze.

I think you'll learn the most by adding it and seeing it in action to see what we are working with.

Adding Prisma to a Next.js project

Alright, let's start up a new blank Next.js project so everyone can follow along from scratch.

npx create-next-app
Enter fullscreen mode Exit fullscreen mode

Give your app a name and navigate inside this new folder.

Then we need to install the Prisma development dependency like so:

npm i -D prisma
Enter fullscreen mode Exit fullscreen mode

While we're here, let's also add the Prisma client we need to do any calls.

npm install @prisma/client
Enter fullscreen mode Exit fullscreen mode

Connecting Prisma to our database

For this example, I'll be using the free Postgres database we created in the article before this one.

To initialize Prisma, we can run this command inside our project.

npx prisma init
Enter fullscreen mode Exit fullscreen mode

This will add a new entry in our .env file for the database, and more importantly, it creates a prisma/schema.prisma file.

This file is the brain of the operation as it holds all the information we need.

Open this file, and let's add our first model.
I'll be adding a playlist model.

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

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

model Playlist {
  id           Int    @default(autoincrement()) @id
  title        String
  image        String
  uri          String
}
Enter fullscreen mode Exit fullscreen mode

As you can see, the type definition for a playlist is pretty simple.
Above that is the needed configuration for Prisma.

Then open your .env file and change the DATABASE_URL to your Heroku Postgres URL (or any other Postgres URL).

Now we need to push this schema to our database. We can do that by running the following command.

npx prisma db push
Enter fullscreen mode Exit fullscreen mode

Once it's done, you can open your database, and you should see the following table.

Schema table in Postgres database

I've then added a record directly into this database for testing purposes.

Data in Postgres database

Consuming the database in Next.js

With this data in place, we can try and consume it from our Next.js app.

To make sure the Prisma client is up to date with your schema, you need to run the following command every time your schema changes:

npx prisma generate
Enter fullscreen mode Exit fullscreen mode

Let's create a simple API call that we can test out to retrieve our data.

Create a playlists.js file inside your pages/api folder.

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export default async function handler(req, res) {
  const playlists = await prisma.playlist.findMany();
  res.json(playlists);
}
Enter fullscreen mode Exit fullscreen mode

Here we load the Prisma client and query the client for the playlist table. On there, we run the findMany query.

This will result in an array of objects.

[
   {
      "id":3,
      "title":"Chris super chill mix",
      "image":"https://i.scdn.co/image/ab67706c0000bebbf036b60da9286ccbc023a6f1",
      "uri":"spotify:playlist:1E8HDaDy8mM2otQwsFqRiD"
   }
]
Enter fullscreen mode Exit fullscreen mode

And there you go, we created our first schema, pushed this to our database, and queried it through Prisma!

You can find the complete code on GitHub.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Discussion (7)

Collapse
2color profile image
Daniel Norman

Awesome article Chris! Be sure to also check out Prisma Studio – a GUI for your database. You can run it with the npx prisma studio command :).

Collapse
dailydevtips1 profile image
Chris Bongers Author

Ah yes thanks Daniel!
Haven't really needed it till now, but will definitely check it out

Collapse
paras594 profile image
Paras 🧙‍♂️ • Edited on

Gooood one !...I am using Prisma in one of my project and it is going good. The relations and schema update are easy to understand.

Collapse
dailydevtips1 profile image
Chris Bongers Author

Thanks Paras!

Prisma has been amazing kind of sad I haven't started using it earlier 😂

Collapse
paras594 profile image
Paras 🧙‍♂️

haha... awesome. I saw another article of yours just now, seeding the db in prisma. are you're writing a series on prisma?

Thread Thread
dailydevtips1 profile image
Chris Bongers Author

I do have a couple coming up on Prisma :D
Been enjoying it so keep an eye out ❤️

Thread Thread
paras594 profile image
Paras 🧙‍♂️

Cool, it will be fun :)