0
0
NextJSframework~30 mins

Prisma ORM setup in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Prisma ORM setup
📖 Scenario: You are building a Next.js app that needs to store and retrieve user data from a database. To manage the database easily, you will set up Prisma ORM, which helps you work with databases using JavaScript code.
🎯 Goal: Set up Prisma ORM in a Next.js project by creating the Prisma schema, configuring the database connection, generating the Prisma client, and integrating it into the Next.js app.
📋 What You'll Learn
Create a Prisma schema file with a User model
Add a database connection URL variable
Generate the Prisma client
Create a Prisma client instance and export it for use in the app
💡 Why This Matters
🌍 Real World
Prisma ORM is widely used in web apps to simplify database access and management with type safety and easy queries.
💼 Career
Knowing how to set up and use Prisma ORM is valuable for full-stack developers working with Next.js and databases.
Progress0 / 4 steps
1
Create Prisma schema with User model
Create a file called schema.prisma inside the prisma folder. Inside it, write the datasource block with provider sqlite and url env("DATABASE_URL"). Then add a generator block for prisma-client-js. Finally, define a model User with fields: id Int @id @default(autoincrement()), email String @unique, and name String?.
NextJS
Need a hint?

Remember to use env("DATABASE_URL") for the database URL and define the User model with the exact fields.

2
Add database connection URL in environment variables
In the root of your Next.js project, create a file called .env. Inside it, add the line DATABASE_URL="file:./dev.db" to set the SQLite database file path.
NextJS
Need a hint?

Make sure the environment variable is named exactly DATABASE_URL and points to file:./dev.db.

3
Generate Prisma client
Run the command npx prisma generate in your terminal to generate the Prisma client based on your schema.
NextJS
Need a hint?

Use the exact command npx prisma generate to create the Prisma client.

4
Create and export Prisma client instance
In your Next.js project, create a file called lib/prisma.ts. Inside it, import PrismaClient from @prisma/client. Then create a constant called prisma as a new PrismaClient() instance. Finally, export prisma as the default export.
NextJS
Need a hint?

Make sure to import PrismaClient, create an instance named prisma, and export it as default.