Thuta Learning
Next.js
AdvancedWeb DevelopmentIntermediate

Separating Out a Database Layer

Next.jsLesson 1935 min

What you'll walk away with

  • Organise queries as use-case functions in lib/data guarded by import "server-only"
  • Return small DTOs with only the needed fields instead of whole ORM rows
  • Create the database client once and reuse it across development hot reloads
  • Put input checks and authorization inside data functions so every caller gets them

Explain it simply

A data layer in plain language

A data layer works like a librarian. Instead of walking into the stacks themselves, pages ask for 'the five newest published notes'. The librarian knows where everything is kept, what you are allowed to see, and hands over only the pages you need.

When the database changes or a new rule arrives, you brief one librarian instead of editing every page. Pages stay short, because they only say what they want, never how to find it.

Problem → Why → Solution

The problem: queries scattered across pages

Twelve pages each call db.note.findMany(...) with slightly different filters. One forgets published: true and drafts go public. Another passes the whole author row to a Client Component as a prop, so passwordHash and email end up in the page payload. Renaming one column means editing twelve files.

app/notes/[id]/page.tsx
import { db } from "@/lib/db";
import { AuthorCard } from "./author-card"; // a Client Component

export default async function NotePage({ params }) {
  const { id } = await params;
  const note = await db.note.findUnique({ where: { id }, include: { author: true } });
  // drafts are visible, and author.passwordHash is serialized to the browser
  return <AuthorCard author={note.author} />;
}

Rules need one home

If every caller has to remember rules such as 'never show drafts publicly' and 'never send password hashes to the client', someone will eventually forget. A data layer puts those rules into the single doorway between the database and the UI.

Core concept: server-only use-case functions and DTOs

A data access layer (DAL) is a set of server-only modules such as lib/data/notes.ts. Its functions are named after use cases, not tables: getPublishedNotes(), getNoteForEditing(id), createNote(input). Pages, Server Actions and Route Handlers call these functions, and only the DAL imports the database client. Next.js's data security guide recommends this pattern for new apps.

import "server-only" at the top of a file (from the server-only npm package) marks the module as server-only. If a Client Component imports it, directly or through another file, the build stops with an error. That protects secrets such as the database URL, and the ORM code itself, from ever reaching the browser bundle.

Props passed from a Server Component to a Client Component are serialized into the RSC payload and sent to the browser. So the DAL should return a Data Transfer Object (DTO): a small object holding only the fields the UI needs. Using select in the ORM also shrinks what you fetch from the database. A function wrapped in React's cache() runs its query once per request for the same arguments, so it does not matter if both the layout and the page call it.

The database client itself must be created only once. Each client opens a connection pool, and the development server re-runs modules on every edit. Storing the client on globalThis and reusing it is the standard pattern shown in ORM docs; in production the module loads once, so the trick is unnecessary there.

LayerResponsibility
Page / Server Actionask for data, render it or request a change
lib/data (DAL)check input and permission, query, return a DTO
lib/dbcreate and share one database client
The doorway between pages and the database
  1. Page asks for a use case, not SQL
  2. DAL checks input and permission
  3. Query selects only needed fields
  4. Returns a small, typed DTO

No file outside lib/db and lib/data should import the database client; if one does, it is going around the doorway.

General pattern

tsx
// lib/data/<resource>.ts
import "server-only";
import { db } from "@/lib/db";

export async function getThingForUi(id: string): Promise<ThingDto | null> {
  if (!isValidId(id)) return null;                    // check input
  await assertCanRead(id);                            // check permission
  const row = await db.thing.findFirst({ where: { id }, select: neededFields });
  return row ? toDto(row) : null;                     // only what the UI needs
}

Write one function per use case in a server-only module, and do the input, permission, select and DTO steps inside that function.

Worked example: a DAL for notes

The first file creates the database client once; the second exposes two use cases for pages. Note that getNoteById does more than fetch a row by id: it checks that the note is published so drafts never leak, uses select to return only the columns the page needs, and is wrapped in cache() so repeated calls within one request hit the database once.

Prisma is only the example here; the pattern is the same with Drizzle or a plain SQL client. Newer ORM versions may change how the client is imported, so check your ORM's Next.js setup guide first. Pages only ever see the exports of these two files.

lib/data/notes.ts
// lib/db.ts (Prisma shown; follow your ORM's documented Next.js setup)
import "server-only";
import { PrismaClient } from "@prisma/client";

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

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

export type NoteSummary = { id: string; title: string; updatedAt: Date };

export async function getPublishedNotes(): Promise<NoteSummary[]> {
  return db.note.findMany({
    where: { published: true },
    select: { id: true, title: true, updatedAt: true },
    orderBy: { updatedAt: "desc" },
  });
}

export const getPublishedNote = cache(async (id: string) => {
  if (!id) return null;
  return db.note.findFirst({
    where: { id, published: true },
    select: { id: true, title: true, body: true, updatedAt: true },
  });
});

Code breakdown

  1. One client in developmentexport const db = globalForDb.db ?? new PrismaClient();

    In development, modules re-run on every edit; storing the client on globalThis and reusing it stops each reload from opening a new connection pool.

  2. Build-time guardimport "server-only";

    A Client Component importing this file fails the build, instead of leaking a secret at runtime.

  3. The rule lives herewhere: { published: true },

    The rule 'no drafts in public lists' lives on this one line; pages no longer have to remember it.

  4. Select is the DTOselect: { id: true, title: true, updatedAt: true },

    Only three fields are fetched and returned, matching the NoteSummary return type; fields such as the author's email never appear.

  5. Deduplicate per requestexport const getPublishedNote = cache(async (id: string) => {

    If generateMetadata and the page both call it with the same id, the query runs once per request.

You should see
Pages call getPublishedNotes() and receive only id, title and updatedAt. Drafts never come back, and importing lib/data/notes.ts from a Client Component fails the build.

Authorization belongs in the data layer too

When loading data for an edit page, check 'may this user edit this note' inside the function itself, so a new page or Route Handler cannot forget the check. Scoping the query itself by ownerId means passing someone else's id simply returns null.

Checking authorization once in the UI and again in the data layer can feel redundant. The UI check only decides whether to show a button; the data layer check is the real protection. Lesson 20 builds these helpers in detail.

lib/data/notes.ts
export async function getNoteForEditing(id: string) {
  const user = await getCurrentUser(); // from lib/auth, also server-only
  if (!user) return null;
  return db.note.findFirst({
    where: { id, ownerId: user.id }, // someone else's id finds nothing
    select: { id: true, title: true, body: true, published: true },
  });
}

In real projects

In real projects

As a project grows, the data layer keeps changes in one place. In each example below the change touches one or two files and no pages, which also makes code review much easier, because a reviewer only has to read the DAL to know every rule.

  • Soft delete: adding deletedAt: null inside the DAL functions hides deleted records from the whole app.
  • Multi-tenant SaaS: the DAL adds a tenantId filter to every query, so one customer never sees another's data.
  • Switching ORMs: moving from Prisma to Drizzle means rewriting lib/data only, because the function signatures stay the same.
  • Testing: DAL functions are tested on their own against a test database, and component tests replace them with fakes.

Common mistakes

Common data layer mistakes

Importing the ORM client or a secret into a Client Component

A "use client" file importing a database module fails the build at best and ships configuration values in the bundle at worst. Put import "server-only" in every DAL file and hand data to client code only as props from a Server Component.

Selecting far more fields than needed

include: { author: true } brings passwordHash, email and internal notes along, and passing that to a Client Component makes it visible in view-source. Select only what the UI needs.

Creating a new client per request or per reload

Calling new PrismaClient() inside a function, or not caching it on globalThis in development, exhausts connections and ends in 'too many connections' errors.

Scattering filters across pages

When filters such as published, tenantId or deletedAt live in each page, one of them will be forgotten. Move them into the DAL function.

Best practices

Best practices

  • Name functions after what they return: getPublishedNotes says more than getNotes.
  • Declare DTO return types and keep the ORM's model types out of the UI.
  • Let mutation functions take one input object and run their own validation.
  • Wrap read functions that are called several times per request in React's cache().

Mini challenge

Mini challenge: an in-memory data layer

Fake the database rows with an array and write three data layer functions: toDto, which drops private fields; getNotesByUser, which returns an error result without querying when userId is missing; and getPublicNote, which returns only published notes.

  • toDto returns an object with only id, title and published
  • getNotesByUser returns { ok: false, error } when userId is missing or blank
  • getPublicNote returns null for a draft id
  • ownerEmail and internalScore never appear in the output
notes-dal.ts
type NoteRow = {
  id: string;
  ownerId: string;
  title: string;
  published: boolean;
  ownerEmail: string;
  internalScore: number;
};
type NoteDto = { id: string; title: string; published: boolean };
type Result<T> = { ok: true; data: T } | { ok: false; error: string };

const rows: NoteRow[] = [/* TODO: a few rows, published and draft */];

function toDto(row: NoteRow): NoteDto {
  // TODO: copy only the fields the UI needs
}

function getNotesByUser(userId: string | undefined): Result<NoteDto[]> {
  // TODO: error result for a missing or blank userId, without touching rows
}

function getPublicNote(id: string): NoteDto | null {
  // TODO: only published notes are visible to the public
}

// TODO: print a few calls, including a missing userId and a draft id

Expected: A missing userId gives {"ok":false,"error":"userId is required"}; u1 gets two notes as DTOs; the draft id gives null; and the fields reaching the UI are only id, title and published.

Show hint

Do not use { ...row } in toDto; copy each field by name, so a field added to the row later does not flow to the UI automatically.

Show solution
notes-dal.ts
type NoteRow = {
  id: string;
  ownerId: string;
  title: string;
  published: boolean;
  ownerEmail: string;
  internalScore: number;
};
type NoteDto = { id: string; title: string; published: boolean };
type Result<T> = { ok: true; data: T } | { ok: false; error: string };

const rows: NoteRow[] = [
  { id: "n1", ownerId: "u1", title: "Hello", published: true,
    ownerEmail: "ada@example.com", internalScore: 7 },
  { id: "n2", ownerId: "u1", title: "Draft idea", published: false,
    ownerEmail: "ada@example.com", internalScore: 2 },
  { id: "n3", ownerId: "u2", title: "Other user", published: true,
    ownerEmail: "bo@example.com", internalScore: 5 },
];

let queries = 0;

function toDto(row: NoteRow): NoteDto {
  return { id: row.id, title: row.title, published: row.published };
}

function getNotesByUser(userId: string | undefined): Result<NoteDto[]> {
  if (!userId?.trim()) return { ok: false, error: "userId is required" };
  queries++;
  return { ok: true, data: rows.filter((r) => r.ownerId === userId).map(toDto) };
}

function getPublicNote(id: string): NoteDto | null {
  queries++;
  const row = rows.find((r) => r.id === id && r.published);
  return row ? toDto(row) : null;
}

console.log("getNotesByUser(undefined) ->", JSON.stringify(getNotesByUser(undefined)));
console.log("getNotesByUser('  ') ->", JSON.stringify(getNotesByUser("  ")));
console.log("getNotesByUser('u1') ->", JSON.stringify(getNotesByUser("u1")));
console.log("getPublicNote('n2') ->", JSON.stringify(getPublicNote("n2")));
console.log("getPublicNote('n1') ->", JSON.stringify(getPublicNote("n1")));
console.log("fields sent to the UI:", Object.keys(toDto(rows[0])).join(", "));
console.log("queries run:", queries);

Quick quiz 1 / 3

What happens when a Client Component imports a module that starts with import "server-only"?

Quick quiz 2 / 3

A Server Component passes a whole ORM user row as a prop to a Client Component that only shows user.name. What is the risk?

Quick quiz 3 / 3

In development, after several file edits, the database reports 'too many connections'. What is the most likely cause?

What to remember

  • Gather queries into use-case functions in lib/data, and let only the DAL import the database client.
  • import "server-only" catches accidental imports from Client Components at build time.
  • Data passed to Client Components is serialized to the browser, so use select and DTOs.
  • Create the client once, and keep filters such as published, tenantId and ownerId, plus authorization, inside the DAL.

Next.js — Fetching Data — Next.js

Next.js — Fetching Data — Next.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.