Skip to main content

The Complete Guide to CRUD Operations in Next.js with Prisma Client - Part 2

Introduction

In this tutorial, we will learn how to create, update, and delete records in Next.js using API routes. We will be using Prisma client to connect to the database and perform these operations. By the end of this tutorial, you will have a clear understanding of how to implement these functionalities in your Next.js applications.

Setting Up the Database Connection

To get started, we need to establish a connection to the database. For this tutorial, we will be using Prisma client. First, install the Prisma client by running the following command:

  • npm install @prisma/client

Next, create a new file called "prisma.js" and add the following code:

rootfolder/db/index.ts

const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

module.exports = prisma;

In this file, we import the PrismaClient from the "@prisma/client" package and create an instance of it. Finally, we export the Prisma client instance to be used in other files.

    

Creating the "todos" Table

schema.prisma file
generator client { provider = "prisma-client-js" } datasource db { provider = "postgresql" url = "postgres://postgres:password@localhost:5433/postgres?schema=public" } model Todos { id Int @id @default(autoincrement()) name String userName String createdAt DateTime @default(now()) }

We can create this table using the Prisma client. Open the terminal and run the following command:

  • npx prisma migrate dev --name init

This command will create the "todos" table in the database based on the schema defined in the Prisma client. Once the migration is complete, you can verify the table in your Postgres database or by using Prisma Studio, a visual interface for exploring and managing your database.

Creating the Delete Method

Now, let's implement the delete functionality for the "todos" table. In the API route file for the "todos" table, duplicate the existing method and change its name to "delete". This method will handle the deletion of a record.

/pages/api/todos/[id].ts


      export default async function handler(req: NextApiRequest, res: NextApiResponse) {
      if (req.method === 'DELETE') {
          try {
              const todoId = req.query.id;
              const todos = await prisma.todos.delete({
                  where: {
                      id: Number(todoId)
                  }
              })
              res.status(200).json(todos);
          } catch (e) {
              res.status(500).json(e);
          }
      } 
     }
      
      

In this code, we extract the "id" from the request body and use it to delete the corresponding record from the "todos" table. The deleted record is then returned as the response.

To test the delete functionality, make a request to the API route with the method set to "delete" and provide the "id" of the record you want to delete. After successful deletion, verify the changes in the database or in Prisma Studio.

Creating the Post Method

Next, let's implement the create functionality for the "todos" table. Duplicate the existing method in the API route file and change its name to "post". This method will handle the creation of a new record.


       

/pages/api/todos/index.ts

export default async function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method === 'POST') { try { const { name, userName } = req.body; const todos = await prisma.todos.create({ data: { name, userName } }) res.status(200).json(todos); } catch (e) { res.status(500).json(e); } } }

In this code, we extract the "name" and "username" from the request body and use them to create a new record in the "todos" table. The newly created record is then returned as the response.

To test the create functionality, make a request to the API route with the method set to "post" and provide the "name" and "username" for the new record. After successful creation, verify the changes in the database or in Prisma Studio.

Creating the Put Method

Finally, let's implement the update functionality for the "todos" table. Duplicate the existing method in the API route file and change its name to "put". This method will handle the update of an existing record.

/pages/api/todos/[id].ts


export default async function handler(req: NextApiRequest, res: NextApiResponse) {
     if (req.method === 'PUT') {
        try {
            const todoId = req.query.id;
            const { name, userName } = req.body;
            const todos = await prisma.todos.update({
                data: {
                    name, userName
                },
                where: {
                    id: Number(todoId)
                }
            })
            res.status(200).json(todos);
        } catch (e) {
            res.status(500).json(e);
        }
    }
}
      

In this code, we extract the "id", "name", and "username" from the request body and use them to update the corresponding record in the "todos" table. The updated record is then returned as the response.

To test the update functionality, make a request to the API route with the method set to "put" and provide the "id" of the record you want to update, along with the updated "name" and "username". After successful update, verify the changes in the database or in Prisma Studio.

Conclusion

In this tutorial, we learned how to create, update, and delete records in Next.js using API routes. We used Prisma client to connect to the database and perform these operations. By following the steps outlined in this tutorial, you should now be able to implement these functionalities in your own Next.js applications.

If you have any questions or need further clarification on any of the topics discussed in this tutorial, please feel free to reach out to us. We hope you found this tutorial informative and helpful. Thank you for watching!

Comments

Popular posts from this blog

Ultimate Guide to Implementing DELETE Operations in Next.js with Prisma

In this tutorial, we will learn how to delete a post in Next.js using the API and UI code. Deleting a post requires making changes to the folder structure and implementing the delete method. Let's dive in! Changing the Folder Structure Currently, the folder structure for the API is not suitable for deleting posts. We need to pass an ID to delete a specific post. To enable this functionality, we will need to alter the folder structure. Here's how: Create a new folder named "posts" within the API directory. Move the existing file into the "posts" folder. Rename the file to "index". Now, when we access the "posts" endpoint, it will work without specifying the file name. Implementing the Delete Method To delete a post, we need to create a new file in the "posts" folder and pass the I...

Creating API Routes for a Full Stack Application

In this blog post, we will explore how to create API routes for a full stack application. API routes are essential for connecting the frontend components to the backend database and fetching data. We will specifically focus on creating the API routes and endpoints for making API calls and retrieving data. Setting up the Database Before we dive into creating the API routes, we need to set up the database. In this example, we will be using a local PostgreSQL database. To connect to the database, we have a schema file that defines a table called "todos" with four fields: id, name, username, and created_at. Currently, we have two records in the todos table. The next step is to write the API routes to connect to the database and fetch the data. Using Prisma for API Routing To create the API routes, we will be using the Prisma library, specifically the Prisma client. The Prisma client allows us to connect to the database and execute queries. To start with the API rout...

How to use Redux in Next.js

Introduction In this blog post, we will explore how to use Redux with Next.js and create todo and disptach it to Redux store and and pass the todo (state) to a Page and display the created Todo. We will cover the process of setting up the necessary Redux store and cover the end to end flow. Create Next.js application npx create-next-app@latest Install dependencies npm install --save @reduxjs/toolkit npm install --save react-redux npm install --save redux-persist Folders and files needed Create folder lib under src folder(src/lib) Create Interface Todos under lib folder (lib/Todos.ts) export interface ITodo { todosState: [Todo] } export interface Todo { todoName: string, description: string, userName: string, id: string } Create folder store under lib (lib/store) Create fi...