Design Converter
Education
Software Development Executive - I
Last updated on Nov 5, 2024
Last updated on Nov 5, 2024
To start, create a new Next.js project using the create-next-app
command:
1npx create-next-app@latest project-name
After creating the project, navigate to the new project folder and start the development server:
1cd project-name 2npm run dev
Install Prisma and its client library:
1npm install prisma @prisma/client
Or, if using yarn:
1yarn add prisma @prisma/client
Initialize Prisma to generate the necessary files:
1npx prisma init
This command creates a prisma
folder with a schema file (schema.prisma
) and a .env
file for environment variables.
Ensure PostgreSQL is set up locally or on a cloud platform like AWS RDS or Heroku. Use the connection string format: postgresql://USER:PASSWORD@HOST:PORT/DATABASE
.
Add the PostgreSQL connection string to .env
:
1DATABASE_URL="postgresql://USER:PASSWORD@HOST:PORT/DATABASE"
1npx prisma init
After defining your schema, generate the Prisma Client:
1npx prisma generate
Define your models in schema.prisma
. For instance, here’s a basic example of a User
model:
1model User { 2 id Int @id @default(autoincrement()) 3 name String 4 email String @unique 5 posts Post[] 6} 7 8model Post { 9 id Int @id @default(autoincrement()) 10 title String 11 content String? 12 authorId Int 13 author User @relation(fields: [authorId], references: [id]) 14}
To sync your models with the database:
1npx prisma migrate dev --name init
Use getServerSideProps
to fetch data with Prisma for SSR:
1// pages/index.js 2 3import prisma from '../lib/prisma' 4 5export async function getServerSideProps() { 6 const users = await prisma.user.findMany() 7 return { props: { users } } 8} 9 10export default function Home({ users }) { 11 return ( 12 <div> 13 {users.map(user => ( 14 <p key={user.id}>{user.name}</p> 15 ))} 16 </div> 17 ) 18}
For SSG, use getStaticProps
:
1// pages/posts.js 2 3import prisma from '../lib/prisma' 4 5export async function getStaticProps() { 6 const posts = await prisma.post.findMany() 7 return { props: { posts } } 8} 9 10export default function Posts({ posts }) { 11 return ( 12 <div> 13 {posts.map(post => ( 14 <p key={post.id}>{post.title}</p> 15 ))} 16 </div> 17 ) 18}
To create API routes for CRUD operations:
1// pages/api/users.js 2 3import prisma from '../../lib/prisma' 4 5export default async function handler(req, res) { 6 if (req.method === 'GET') { 7 const users = await prisma.user.findMany() 8 res.json(users) 9 } 10}
To retrieve data, use functions like findMany
and findUnique
:
1const users = await prisma.user.findMany() 2const user = await prisma.user.findUnique({ 3 where: { id: 1 }, 4})
Use create
, update
, and delete
for data mutations:
1// Create 2const newUser = await prisma.user.create({ 3 data: { name: 'Alice', email: 'alice@example.com' }, 4}) 5 6// Update 7const updatedUser = await prisma.user.update({ 8 where: { id: 1 }, 9 data: { email: 'new-email@example.com' }, 10}) 11 12// Delete 13await prisma.user.delete({ 14 where: { id: 1 }, 15})
To open Prisma Studio for an interactive interface to manage data:
1npx prisma studio
Create a prisma.js
file in the lib
folder:
1// lib/prisma.js 2 3import { PrismaClient } from '@prisma/client' 4 5let prisma 6 7if (process.env.NODE_ENV === 'production') { 8 prisma = new PrismaClient() 9} else { 10 if (!global.prisma) { 11 global.prisma = new PrismaClient() 12 } 13 prisma = global.prisma 14} 15 16export default prisma
Prisma Accelerate or native pooling libraries are helpful for managing connections in serverless environments.
Use TypeScript with Prisma to improve type safety. Prisma automatically generates TypeScript types based on your schema, making data handling safer.
Deploying Prisma with Next.js on Vercel is straightforward:
Use .env
for local development. In production, manage variables through Vercel's Environment Variables settings.
Maintain a single instance of Prisma Client to avoid connection exhaustion:
1// lib/prisma.js (as defined above)
To protect schema details, avoid exposing the Prisma schema directly to the client side, and restrict sensitive data.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.