Back to writing

📡

Setup Next.js App Directory and Prisma ORM

August 9, 2024

5 min read

Cover

# Introduction

This guide provides a comprehensive walkthrough for setting up a Next.js application integrated with Prisma ORM. It covers the initial setup, configuration, and basic CRUD operations to get you started with a robust development foundation.

# Installing Nextjs

Setting up Next.js is straightforward with support for multiple package managers. Choose the one that best fits your workflow:

npx create-next-app my-next-app
cd my-next-app
bash

# Installing Prisma

To integrate Prisma into your Next.js application, install Prisma Client and the Prisma CLI as follows:

npm install @prisma/client
npm install prisma --save-dev
npx prisma init
bash

# Folder Structure

Folder structure yang saya gunakan adalah seperti ini:

.
├── next.config.js
├── next-env.d.ts
├── node_modules
├── package.json
├── postcss.config.cjs
├── prettier.config.js
├── prisma
│   ├── db.sqlite
│   ├── migrations
│   │   ├── 20240701154234_init
│   │   │   └── migration.sql
│   │   └── migration_lock.toml
│   └── schema.prisma
├── public
├── README.md
├── src
│   ├── app
│   ├── server
│   │   └── db.ts
├── tailwind.config.ts
├── tsconfig.json
├── yarn-error.log
└── yarn.lock
plaintext

# Prisma Setup

Configure your Prisma environment by setting up the schema and initializing the database connection:

generator client {
    provider        = "prisma-client-js"
}
 
datasource db {
    provider = "sqlite"
    url      = "file:./dev.db"
}
 
model User {
    id            String    @id @default(cuid())
    name          String?
    email         String?   @unique
 
    @@map("users")
}
prisma

# Using Prisma

## Database Migrations with Prisma

Prisma Migrate is a powerful feature that helps you manage your database schema through code. You can create and apply migrations that are based on changes in your Prisma schema.

### Creating Migrations

When you make changes to your schema.prisma, you need to create a migration file that Prisma can use to update the database schema:

npx prisma migrate dev --name describe_your_migration
bash

This command will generate SQL migration files in the prisma/migrations directory and immediately apply them to your development database. It's ideal for local development environments.

### Applying Migrations in Production

To deploy your migrations in a production environment, you should use the migrate deploy command which skips the generation step:

npx prisma migrate deploy
bash

This command applies all pending migrations for your production database. It's crucial to perform this step after you have tested the migrations in a staging or another safe testing environment.

## Syncing Database Schema

If you prefer to sync your database schema directly without creating migration files, you can use Prisma DB Push. This is particularly useful during early development stages but not recommended for production environments.

npx prisma db push
bash

## Generating Prisma Client

To interact with your database, generate the Prisma Client based on your current schema:

npx prisma generate
bash

The prisma generate command reads your Prisma schema and generates or updates the Prisma Client. You should run this command after every change to your schema or after pulling changes that include schema modifications.

# Using Prisma in Next.js Server Components

Next.js 14 introduces enhanced support for server components, allowing direct integration of backend operations within your React components. This section demonstrates how to use the db object from Prisma to perform database queries directly from a server component.

## Example: Fetching User Data

Creating a server component that fetches user data from the database using Prisma. This component will run exclusively on the server, ensuring that database credentials and queries do not expose to the client.

@/components/UserLists.tsx
import { db } from '@/server/db'; // Adjust the path according to your project structure
 
export default async function UserList() {
  const users = await db.user.findMany(); // Fetch all users
  return (
    <div>
      <h1>User List</h1>
        <ul>
          {users.map(user => (
            <li key={user.id}>{user.name}</li>
          ))}
        </ul>
    </div>
  );
}
tsx

# Conclusion

With the above configurations, your Next.js application is now set up with Prisma ORM. This setup will assist you in managing your database operations efficiently, and you can extend this setup to include advanced features as your application grows.