0
0
NextJSframework~5 mins

Why database access matters in NextJS

Choose your learning style9 modes available
Introduction

Database access lets your app save and get information. This makes your app useful and interactive.

You want to save user sign-up details so they can log in later.
You need to show a list of products that can change over time.
You want to store user preferences to personalize their experience.
You need to keep track of orders or transactions in an online store.
You want to update content without changing the app code.
Syntax
NextJS
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.

Examples
Get all users from the database.
NextJS
const users = await prisma.user.findMany();
Add a new post with a title.
NextJS
const post = await prisma.post.create({ data: { title: 'Hello' } });
Find a user by their unique ID.
NextJS
const user = await prisma.user.findUnique({ where: { id: 1 } });
Sample Program

This Next.js component fetches all users from the database and shows their names in a list.

NextJS
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>
  );
}
OutputSuccess
Important Notes

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.

Summary

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.