TechSolution

Programing tutorial

Prisma integration in Nextjs app Router

prisma nextjs

Prisma is an open-source data access layer that simplifies database management in modern applications. It offers a strong API to communicate with databases and supports various databases like PostgreSQL, MySQL, MongoDB, etc. Integrating Prisma with a Next.js app can boost database management and app performance, as well as increase reliability and security with its type safety and data protection features

This section we will create an integration of Nextjs app router, Prisma as the ORM and Mysql

Run the following command to install our nextjs project and select typescript:

Install Project Nextjs

npx create-next-app@latest

Instal Prisma

After the project has finished downloading, we then install and configure Prisma on the project.

yarn add @prisma/client
yarn add -D prisma
yarn add -D ts-node

Create provider

Then Create Provider for prisma database. Now you can create your database in local

yarn prisma init --datasource-provider mysql

Edit file .env depends on your database configuration

DATABASE_URL="mysql://root:123@localhost:3306/nextjs13_fullstack"

Generate Prisma Client

yarn prisma generate

Add model to scheme.prisma

Now We create a model named user

..........before code.......
model User {
  id        String   @id @default(uuid())
  name      String
  email     String   @unique
  role      String
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

Create Migrate

yarn prisma migrate dev --name init

After run migrate now in our database will create a new table user

Seeed the Database

We can use seed to populate users table

Create file seed.ts

  • prisma/seed.ts
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();

async function main() {
  const user = await prisma.user.upsert({
    where: { email: "admin@admin.com" },
    update: {},
    create: {
      name: "Rafles",
      email: "Rafles@gmail.com",
      role: "admin"
    },
  });
  console.log({ user });
}

main()
  .catch(async (e) => {
    console.error(e);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

Add Seed in package.json

Add seed in package.json for ruunning seed.

  {
  "prisma": {
    "seed": "ts-node --compiler-options {\"module\":\"CommonJS\"} prisma/seed.ts"
  }
}

run command seed

 yarn prisma db seed

Now in our table user will create a new data row

Initiate the Prisma Client for Project

create Prisma file configuration

Create a file in src/lib/prisma.ts . This file is use to integration prisma and database

//src/lib/prisma.ts
import { PrismaClient } from "@prisma/client";

const globalForPrisma = global as unknown as { prisma: PrismaClient };

export const prisma =
  globalForPrisma.prisma ||
  new PrismaClient({
    log: ["query"],
  });

if (process.env.NODE_ENV != "production") globalForPrisma.prisma;

Call prisma in Any Page Our Component

Now we have ready to use prisma in our project. Look like below.


import Image from "next/image";
import { stringify } from "querystring";
import { prisma } from "@/lib/prisma";

export default async function UserPage() {
  const dataUser = await getDataWithPrisma();

  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <div>
        <h3>Access DB with Prisma CLient </h3>
        <hr />
        <br />
        {dataUser.map((val, i): any => {
          return (
            <div key={i} style={{ marginBottom: "30px" }}>
              <p>{val.id}</p>
              <p>{val.name}</p>
              <p>{val.email}</p>
              <hr />
            </div>
          );
        })}
      </div>
    </main>
  );
}

async function getDataWithPrisma() {
  let users = await prisma.user.findMany();
  return users;
}

Now we have success integration prisma in our nextjs app router.

Happy Coding!

By raflesngln@gmail.com

Stay Hungry Stay Foolish

2 thoughts on “Prisma integration in Nextjs app Router”

Leave a Reply

Your email address will not be published. Required fields are marked *