Next.js and Prisma – Setup Schema, APIs and Error handling with Examples

In this tutorial, you will learn about Prisma and how we can use it in our Next js application and what are its advanced use cases. What is Prisma? Prisma is a powerful open-source toolkit which replaces the traditional Object-Relational Mappings (ORMs) and can be easily used to build GraphQL servers, REST APIs, microservices etc.…

By.

min read

In this tutorial, you will learn about Prisma and how we can use it in our Next js application and what are its advanced use cases.

What is Prisma?

Prisma is a powerful open-source toolkit which replaces the traditional Object-Relational Mappings (ORMs) and can be easily used to build GraphQL servers, REST APIs, microservices etc.

Object-Relational Mapping (ORM) is a programming technique which helps to interact with their database like we do with SQL. It creates an object in the programming language that refers to each table in the database and these objects are used to perform database operations.

 

Here are some of the key features of Prisma:

  • It supports type-safe and autogenerated query builder with Prisma Client.
  • Helps in data modelling and migrations using Prisma Schema and Prisma Migrate.
  • Data can be visualised using Prisma Studio
  • It supports and works with many types of databases including PostgreSQL, MySQL, SQLite etc.

 

Combining Next.js and Prisma

By combining both Next.js and Prisma we can develop a robust solution for building server-side rendered applications having excellent data management capabilities. This synergy can exhibit the following benefits:

  • Making data fetching on the server-side pretty streamlined.
  • The database access becomes type-safe.
  • Data management becomes a simplified process
  • Uisnf Prisma improved the performance and security of the whole system.

 

How to use Prisma in Next js?

Follow these quick steps to create a simple app using Prisma in the Next js application:

Step 1: Setting Up the Project
Step 2: Setup Prisma in Project
Step 3: Configuring the Database
Step 4: Generate Prisma Client
Step 5: Creating the API Routes
Step 6: Running the Application

 

Step 1: Setting Up the Project

First, create a new Next.js application and navigate into the project directory:

npx create-next-app@11 next-prisma-app
cd next-prisma-app

 

Step 2: Setup Prisma in Project

Next, we will set up Prisma in our Next js application we just created. Execute the following npx command:

npx prisma init

This will create a prisma directory in your project root which will have a file named schema.prisma to contain all the schema.

 

Step 2: Configuring the Database

The prisma directory is having a file named schema.prisma. This file will have the database connection and models details in it. For example, we will use SQLite and update our schema.prisma file as follows:

datasource db {
  provider = "sqlite"
  url      = "file:./dev.db"
}

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

model User {
  id    Int     @id @default(autoincrement())
  name  String
  email String  @unique
}

 

Step 3: Generate Prisma Client

Now, we will generate the Prisma Client, which will help us to interact with our database. Execute the following command to do that:

npx prisma generate

 

Step 4: Creating the API Routes

Thereafter, we will create some API routes for our CRUD operations. In the pages/api directory, create a new file named user.js and update with following:

// pages/api/user.js
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

export default async function handle(req, res) {
  if (req.method === 'POST') {
    const { name, email } = req.body
    const user = await prisma.user.create({
      data: {
        name,
        email,
      },
    })
    res.json(user)
  } else if (req.method === 'GET') {
    const users = await prisma.user.findMany()
    res.json(users)
  } else if (req.method === 'PUT') {
    const { id, name, email } = req.body
    const user = await prisma.user.update({
      where: { id: Number(id) },
      data: { name, email },
    })
    res.json(user)
  } else if (req.method === 'DELETE') {
    const { id } = req.body
    const user = await prisma.user.delete({
      where: { id: Number(id) },
    })
    res.json(user)
  }
}

 

Step 5: Running the Application

Finally, you can run your application:

npm run dev

Now you will be able to perform the CRUD operations by making the HTTP request to this http://localhost:3000/api/user.

For example, to create a user, you can make a POST request with a body of { "name": "Alice", "email": "[email protected]" }.

 

Advanced Next.js Prisma Concepts

While working with Next js and Prisma, you will learn advanced concepts like data modeling, migrations and error handling. Let’s have a quick look at these one by one to have better understanding to scratch the surface.

 

Data Modeling with Prisma

In Prisma, data modeling is done using the Prisma Schema Language (PSL). Here’s an example of a Prisma data model:

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}

model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String?
  published Boolean  @default(false)
  author    User     @relation(fields: [authorId], references: [id])
  authorId  Int
}

 

Migrations with Prisma

Prisma Migrate is a database schema migration tool which is fully integrated into Prisma and enables data modelling from the application layer. It helps in evolving the database schema using declarative data models and maintains a version history of schema changes.

 

Error Handling in Next.js Prisma Applications

During the interaction with remote APIs, error handling becomes a crucial aspect. We can handle the error using the try-catch blocks for example:

// pages/api/user.js
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

export default async function handle(req, res) {
  const { name, email } = req.body
  try {
    const result = await prisma.user.create({
      data: {
        name,
        email,
      },
    })
    res.json(result)
  } catch (error) {
    res.status(400).json({ error: 'Something went wrong' })
  }
}

 

Conclusion

We have completed the integration of Prisma in our Next js application. We discussed various features and advantages of using Prisma in the Next js project. Also, create followed quick steps for easy integration and setting up of schema and API routes for CRUD operations. Moreover, we looked int to the advanced concepts with examples on error handling, Modeling etc. Hope this was helpful.

Leave a Reply

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