Menu

Working with Databases

Lesson 3: Working with Databases

How do you use a database in Next.js?

Server Components and Server Actions run on the server, so they can query a database directly. Most projects use an ORM (object-relational mapper) for type-safe queries.

Tool Style Strength
Prisma Schema file + generated client Beginner-friendly, migrations, studio UI
Drizzle ORM SQL-like TypeScript API Lightweight, close to SQL
Kysely Type-safe query builder Fine control without a full ORM
Provider SDKs (Supabase, Firebase, MongoDB) Client library Hosted services with auth and storage

Example (Prisma)

// prisma/schema.prisma
model Course {
  id        String   @id @default(cuid())
  slug      String   @unique
  title     String
  level     String
  price     Int      // in paise
  published Boolean  @default(false)
  createdAt DateTime @default(now())
}
// lib/db.ts – one client, reused across hot reloads in development
import { PrismaClient } from '@prisma/client';

const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };
export const db = globalForPrisma.prisma ?? new PrismaClient();
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = db;

The data access layer (DAL)

Keep all database access in one folder, such as lib/data/, rather than scattering queries across components.

// lib/data/courses.ts
import 'server-only';
import { cache } from 'react';
import { db } from '@/lib/db';

export const getPublishedCourses = cache(async () => {
  return db.course.findMany({
    where: { published: true },
    select: { id: true, slug: true, title: true, level: true, price: true },
  });
});

How it works

  • server-only guarantees this file is never bundled for the browser.
  • select returns only the fields the UI needs, so private columns never leave the server.
  • The global client pattern prevents "too many connections" errors when files reload in development.
  • Serverless hosts may need a connection pooler (such as Prisma Accelerate, PgBouncer, or the provider's pooled URL).

Common mistakes

Mistake Effect Fix
Creating a new client in every file Connection limit reached Export one shared client
Querying in Client Components Impossible or leaks credentials Query in Server Components or Server Actions
Returning whole rows to the UI Private fields (emails, hashes) exposed Use select and DTOs
Storing money as floats Rounding errors Store the smallest unit (paise) as integers

Key takeaways

  • Query databases directly from server code with an ORM.
  • Centralise queries in a server-only data access layer that returns only safe fields.

Try it: Set up Prisma with SQLite, create the Course model, seed three courses, and render them on the courses page.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details