Introduction
Database access lets your app save and get information. This makes your app useful and interactive.
Jump into concepts and practice - no test required
Database access lets your app save and get information. This makes your app useful and interactive.
import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient(); export async function getServerSideProps() { const data = await prisma.user.findMany(); return { props: { data } }; }
Use PrismaClient or another database client to connect.
Database calls are usually async, so use await.
const users = await prisma.user.findMany();
const post = await prisma.post.create({ data: { title: 'Hello' } });
const user = await prisma.user.findUnique({ where: { id: 1 } });
This Next.js component fetches all users from the database and shows their names in a list.
import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient(); export default async function Page() { const users = await prisma.user.findMany(); return ( <main> <h1>User List</h1> <ul> {users.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> </main> ); }
Always handle database errors to avoid app crashes.
Use server-side code for database access to keep credentials safe.
Keep database queries efficient to avoid slow app responses.
Database access lets your app save and get data.
Use it when you need to store or show changing information.
In Next.js, database calls happen in server-side code for safety and speed.
import { db } from '@/lib/db';
export default async function Page() {
const users = await db.user.findMany();
return (
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
}export default function handler(req, res) {
const users = db.user.findMany();
res.status(200).json(users);
}Option A:
const posts = await db.post.findMany({ include: { author: true } });
return posts.map(p => <div key={p.id}>{p.title} by {p.author.name}</div>);
Option B:
const posts = await db.post.findMany();
const authors = await db.user.findMany();
return posts.map(p => <div key={p.id}>{p.title} by {authors.find(a => a.id === p.authorId).name}</div>);
Option C:
Fetch posts on client side and authors on server side separately.
Option D:
Render posts without author names to speed up loading.