Prisma ORM helps you easily work with databases in your Next.js app. It turns database data into simple JavaScript objects you can use.
Prisma ORM setup in NextJS
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
NextJS
npx prisma init // Then edit prisma/schema.prisma to define your data models // Generate Prisma client npx prisma generate // Use Prisma client in your Next.js code import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient()
npx prisma init creates the basic setup files.
You define your database tables as models in schema.prisma.
Examples
NextJS
model User {
id Int @id @default(autoincrement())
name String
email String @unique
}NextJS
const users = await prisma.user.findMany()
NextJS
const newUser = await prisma.user.create({ data: { name: 'Anna', email: 'anna@example.com' } })
Sample Program
This Next.js compatible code creates a user and then fetches all users from the database. It logs the results to the console.
NextJS
import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient() async function main() { // Create a new user const user = await prisma.user.create({ data: { name: 'John Doe', email: 'john@example.com' } }) // Fetch all users const allUsers = await prisma.user.findMany() console.log('Created user:', user) console.log('All users:', allUsers) } main() .catch(e => console.error(e)) .finally(async () => { await prisma.$disconnect() })
Important Notes
Always run npx prisma generate after changing your schema.
Use environment variables to keep your database URL safe.
Disconnect Prisma client after use to avoid open connections.
Summary
Prisma ORM makes database work simple and safe in Next.js.
Define your data models in schema.prisma.
Use Prisma client to create, read, update, and delete data easily.
Practice
1. What is the primary purpose of the
schema.prisma file in a Next.js project using Prisma ORM?easy
Solution
Step 1: Understand the role of
This file is used to define the data models and how they relate to each other in the database.schema.prismaStep 2: Differentiate from other files in Next.js
API routes and page routing are handled by Next.js files, notschema.prisma. Styling is done with CSS or styling libraries.Final Answer:
To define the database models and their relationships -> Option BQuick Check:
schema.prisma= data models [OK]
Hint: Remember: schema.prisma defines your database structure [OK]
Common Mistakes:
- Confusing schema.prisma with API route files
- Thinking schema.prisma handles styling
- Assuming schema.prisma manages Next.js routing
2. Which of the following is the correct way to import and instantiate the Prisma Client in a Next.js API route?
easy
Solution
Step 1: Check the correct import syntax for Prisma Client
The official way is to import PrismaClient as a named import from '@prisma/client'.Step 2: Instantiate PrismaClient correctly
Use thenewkeyword to create an instance:new PrismaClient().Final Answer:
import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient(); -> Option AQuick Check:
Correct import and instantiation = import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient(); [OK]
Hint: Use named import and new keyword for PrismaClient [OK]
Common Mistakes:
- Using require() instead of import
- Calling PrismaClient as a function without new
- Incorrect import paths or default imports
3. Given the following Prisma model in
schema.prisma:
model Post {
id Int @id @default(autoincrement())
title String
published Boolean @default(false)
}
What will be the result of this Prisma Client query?
const posts = await prisma.post.findMany({ where: { published: true } });
console.log(posts);medium
Solution
Step 1: Understand the Prisma model and query
The model has a Boolean fieldpublished. The query filters posts wherepublishedis true.Step 2: Analyze the query result
findManyreturns an array of all matching posts, so it returns all posts withpublished: true.Final Answer:
An array of posts where published is true -> Option DQuick Check:
findMany with where filter = array filtered by condition [OK]
Hint: findMany returns arrays filtered by where conditions [OK]
Common Mistakes:
- Expecting a single object instead of an array
- Ignoring the where filter and expecting all posts
- Thinking 'published' field does not exist
4. You wrote this code in a Next.js API route:
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
export default async function handler(req, res) {
const user = await prisma.user.findUnique({ where: { id: req.query.id } });
res.json(user);
}
But you get an error: TypeError: Cannot read property 'id' of undefined. What is the likely cause?medium
Solution
Step 1: Identify the error cause
The error saysCannot read property 'id' of undefined, meaningreq.queryis undefined oridis missing.Step 2: Check the API route usage
Ensure the request URL includes a query parameter?id=someValuesoreq.query.idexists.Final Answer:
Thereq.queryobject is undefined or missingid-> Option CQuick Check:
Missing query param causes undefined error [OK]
Hint: Check if query parameters exist before accessing them [OK]
Common Mistakes:
- Assuming PrismaClient instantiation causes this error
- Thinking findUnique method is invalid
- Trying to import res object explicitly
5. You want to add a new model
Comment related to Post in your Prisma schema, where each comment belongs to one post. Which of the following schema additions correctly sets up this relationship?hard
Solution
Step 1: Understand Prisma relations syntax
To relate Comment to Post, Comment needs a foreign keypostIdand a relation fieldpostwith@relationspecifying fields and references.Step 2: Check the Post model for back relation
Post should have acommentsfield as an array of Comment to represent one-to-many relation.Final Answer:
Option A correctly defines the foreign key, relation, and back relation -> Option AQuick Check:
Relation fields with @relation and back array = model Comment { id Int @id @default(autoincrement()) content String postId Int post Post @relation(fields: [postId], references: [id]) } model Post { id Int @id @default(autoincrement()) title String comments Comment[] } [OK]
Hint: Use @relation with fields and references for foreign keys [OK]
Common Mistakes:
- Omitting @relation attribute causing errors
- Not defining back relation array in Post
- Missing foreign key field postId in Comment
