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.
Before we dive into Prisma, let’s first set up a fresh Next.js 15 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
Prisma is available as a development dependency. Install it by running the following commands:
npm install prisma --save-dev
npm install @prisma/client
Now that we have our Next.js project set up, let’s initialize Prisma.
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.
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"
Next, we’ll define a basic User
model in Prisma’s schema to interact with our database.
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())
}
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.
Now it’s time to generate the Prisma Client, which is used to interact with your database in the application.
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.
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.
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.
Now let’s set up an API route that will interact with the database using Prisma.
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.
Next, let’s display the data on the homepage of our app.
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.
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
For production environments, make sure sensitive information (like DATABASE_URL
) is stored securely in environment variables and is not hardcoded into your application.
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.
💥 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. 🚀
👨💻 Programmer | ✈️ Love Traveling | 🍳 Enjoy Cooking | Building cool tech and exploring the world!
View more blogs by me CLICK HERE
Loading related blogs...
In this newsletter we provide latest news about technology, business and startup ideas. Hope you like it.