<Sagar/>

Prisma in Next.js 15 with JavaScript: Step-by-Step Guide

49

Prisma is a modern and powerful Object-Relational Mapping (ORM) tool that simplifies working with databases in JavaScript and TypeScript applications. In this tutorial, we’ll go over how to set up Prisma in a Next.js 15 project using JavaScript. Additionally, we’ll create a singleton file for Prisma to avoid issues with multiple instances during development. Whether you’re building a simple app or a complex database-driven project, Prisma makes it easier to interact with your database efficiently.

Step 1: Set Up Your Next.js 15 Project

Before we dive into Prisma, let’s first set up a fresh Next.js 15 project.

1.1 Create a New Next.js Project

Run the following commands in your terminal to create a new Next.js app:

npx create-next-app@latest my-nextjs-app
cd my-nextjs-app

1.2 Install Prisma and Dependencies

Prisma is available as a development dependency. Install it by running the following commands:

npm install prisma --save-dev
npm install @prisma/client

Step 2: Initialize Prisma

Now that we have our Next.js project set up, let’s initialize Prisma.

2.1 Run Prisma Initialization

Run this command to generate the necessary Prisma configuration files:

npx prisma init

This will create a prisma/ folder, which contains a schema.prisma file and a .env file to store your environment variables.

2.2 Set Up Database Connection

Open the .env file and configure the DATABASE_URL with your database connection string. If you're using PostgreSQL, your .env file might look like this:

DATABASE_URL="postgresql://username:password@localhost:5432/mydatabase"

Step 3: Define Your Prisma Schema

Next, we’ll define a basic User model in Prisma’s schema to interact with our database.

3.1 Update schema.prisma

Open prisma/schema.prisma and add the following code to define a simple User model:

generator client {
  provider = "prisma-client-js"
}
datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}
model User {
  id        Int      @id @default(autoincrement())
  name      String
  email     String   @unique
  createdAt DateTime @default(now())
}

3.2 Apply Your Prisma Schema

To apply the schema changes to your database, run the following command:

npx prisma migrate dev --name init

This will generate the necessary migration files and apply them to your database.

Step 4: Generate the Prisma Client

Now it’s time to generate the Prisma Client, which is used to interact with your database in the application.

4.1 Generate Prisma Client

Run the following command to generate the Prisma Client:

npx prisma generate

The Prisma Client will be created inside the node_modules/@prisma/client directory.

Step 5: Create a Prisma Singleton File

Next, we’ll create a singleton pattern for Prisma. This ensures that only one Prisma Client instance is created, preventing issues with multiple instances in development due to hot reloading.

5.1 Create a Singleton File for Prisma

Inside your project, create a new file lib/prisma.js and add the following code:

import { PrismaClient } from '@prisma/client';
let prisma;
if (process.env.NODE_ENV === 'production') {
  prisma = new PrismaClient();
} else {
  if (!global.prisma) {
    global.prisma = new PrismaClient();
  }
  prisma = global.prisma;
}
export default prisma;

This file ensures that Prisma is only initialized once in development mode and only a single instance is used, preventing unnecessary database connections.

Step 6: Use Prisma in API Routes

Now let’s set up an API route that will interact with the database using Prisma.

6.1 Create an API Route

In the pages/api/ folder, create a new file called users.js. Add the following code to fetch and create users:

import prisma from '../../lib/prisma';
export default async function handler(req, res) {
  if (req.method === 'GET') {
    const users = await prisma.user.findMany();
    res.status(200).json(users);
  } else if (req.method === 'POST') {
    const { name, email } = req.body;
    try {
      const newUser = await prisma.user.create({
        data: { name, email },
      });
      res.status(201).json(newUser);
    } catch (error) {
      res.status(400).json({ error: 'Unable to create user' });
    }
  } else {
    res.status(405).json({ error: 'Method not allowed' });
  }
}

This API route allows us to:

  • GET all users from the database.

  • POST a new user to the database.

Step 7: Use Prisma in Your Pages

Next, let’s display the data on the homepage of our app.

7.1 Fetch Data with getServerSideProps

Open the pages/index.js file and modify it to fetch users from the database:

import prisma from '../lib/prisma';
export async function getServerSideProps() {
  const users = await prisma.user.findMany();
  return {
    props: { users },
  };
}
export default function Home({ users }) {
  return (
    <div>
      <h1>User List</h1>
      <ul>
        {users.map((user) => (
          <li key={user.id}>
            {user.name} ({user.email})
          </li>
        ))}
      </ul>
    </div>
  );
}

This code will fetch the users from the database on the server side and render them on the page.

Step 8: Debug and Optimize

8.1 Use Prisma Studio

To interact with your database, use Prisma Studio. It provides a GUI for your database, making it easy to view and manipulate data.

Run this command to launch Prisma Studio:

npx prisma studio

8.2 Ensure Proper Environment Variables

For production environments, make sure sensitive information (like DATABASE_URL) is stored securely in environment variables and is not hardcoded into your application.

Conclusion

Congratulations! You’ve successfully integrated Prisma into your Next.js 15 project using JavaScript. You now have a fully functional database with Prisma, an optimized singleton Prisma client for handling multiple instances, and the ability to interact with your database through API routes and server-side functions.

By following this tutorial, you’ve built a foundation for creating dynamic, database-driven applications with Next.js and Prisma.

Additional Resources

💥 Did you find this blog helpful? 💥

If you enjoyed this post, please clap and follow for more insights on web development and Next.js! Your support helps me continue sharing useful content to enhance your development journey. 🚀

Prisma
Next.js
JavaScript
Web Development
React
Arnold Gunter

Written by Sagar Sangwan

👨‍💻 Programmer | ✈️ Love Traveling | 🍳 Enjoy Cooking | Building cool tech and exploring the world!

View more blogs by me CLICK HERE

Loading related blogs...

Newsletter subscription

SUBSCRIBE to Newsletter

In this newsletter we provide latest news about technology, business and startup ideas. Hope you like it.