How to use prisma in Next.js?

Prisma is one of the best ORM for javascript, if you want to use it in your next.js application you can follow this tutorial.

First let's install dependency prisma to our next.js projet.

npm install prisma @prisma/client

Configur prisma:

npx prisma init

Next steps:

  1. Set the DATABASE_URL in the .env file to point to your existing database. If your database has no tables yet, read https://pris.ly/d/getting-started
  2. Set the provider of the datasource block in schema.prisma to match your database: postgresql, mysql, sqlite, sqlserver, mongodb or cockroachdb.
  3. Run npx prisma db pull to turn your database schema into a Prisma schema.
  4. Run npx prisma generate to generate the Prisma Client. You can then start querying your database.

If you just started the project run this command to create tables.

First define the schema in prisama/schema.prisma file:

model Youtube {
  id         String  @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
  title      String
  link       String
  channelId  String
  thumbnail  String
  Transcript Transcript[]
}

model Transcript {
  id        String  @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
  text      String
  duration  String
  offset    String
  youtube   Youtube @relation(fields: [youtubeId], references: [id])
  youtubeId String  @db.Uuid
}

Then run the migrations:

npx prisma db push

How to query data.

First setup the sample data, run this sql query:

INSERT INTO "public"."Youtube" ("title", "link", "channelId", "thumbnail") VALUES ('Will technology shape our future or will we | Deborah Nas | TEDxAlkmaar', 'https://www.youtube.com/watch?v=j648moM5j0w', 'UCsT0YIqwnpJCM-mx7-gSA4Q', 'https://i.ytimg.com/vi/j648moM5j0w/maxresdefault.jpg');

Now create new api to get all videos.

File pages/api/videos.ts:

import type { NextApiRequest, NextApiResponse } from "next";
import { PrismaClient } from "@prisma/client";

type Data = {
  data: {
    id: string;
    title: string;
    link: string;
    channelId: string;
    thumbnail: string;
  }[];
};

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  const prisma = new PrismaClient();
  const data = await prisma.youtube.findMany();
  prisma.$disconnect();

  res.status(200).json({ data });
}

Now test the endpoint by calling the endpoint using curl:

curl --request GET \
  --url http://localhost:3000/api/videos \
  --header 'User-Agent: insomnia/8.3.0'

It should give the response like this:

{
  "data": [
    {
      "id": "a246aeab-ad02-4f34-8098-f56935d8cbb7",
      "title": "Will technology shape our future or will we | Deborah Nas | TEDxAlkmaar",
      "link": "https://www.youtube.com/watch?v=j648moM5j0w",
      "channelId": "UCsT0YIqwnpJCM-mx7-gSA4Q",
      "thumbnail": "https://i.ytimg.com/vi/j648moM5j0w/maxresdefault.jpg"
    }
  ]
}

Before you deploy add this script in build scripts.

{
  ...
  "scripts": {
    ...
    "build": "npx prisma generate && next build",
    ...
  }
}