Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 72 ยท Data Fetching and Caching

Data Access Layers and ORMs

Organize database code in Next.js with a data access layer: Prisma and Drizzle queries, DTOs that hide secrets, React cache deduplication and no waterfalls.

Server Components can query a database directly, which is wonderful for small examples and dangerous for big apps. If every page and component writes its own prisma.user.findMany(...), the same query gets copied around, nobody remembers which fields are safe to show, and a security fix has to be applied in twenty places.

The cure is a data access layer (DAL): one folder of server-only functions that are the only code allowed to talk to the database. Pages and components call functions such as getPost(slug) and never see SQL or ORM calls. In this lesson you will build that layer step by step, see how to write it with Prisma or Drizzle, return safe data transfer objects, stop duplicate queries with React's cache, and avoid request waterfalls. It follows from Fetching Data in Server Components.

Why a layer at all

One door to the database

One place Every query lives in lib/data.
Safe output Functions return only fields that are fine to show.
Reuse Many components share one query.
Testable Swap the real database for a fake one.

Components ask for data by meaning, not by SQL.

1 / 2

A typical layout looks like this:

TEXT
lib/
  prisma.ts          the ORM client, created once
  data/
    posts.ts         getPost, listPosts, createPost
    users.ts         getCurrentUser, getProfile
app/
  blog/[slug]/page.tsx   calls getPost(slug)

The first line of every file in lib/data should be import 'server-only'. That package makes the build fail if a Client Component ever imports the file, so your database code and its credentials cannot be bundled for the browser. Keeping Server Code on the Server goes deeper.

Writing the layer with Prisma

An ORM (object-relational mapper) lets you read and write rows through typed JavaScript calls instead of raw SQL. Prisma generates a typed client from your schema file. A read-only example of one DAL function:

TSX
// lib/data/posts.ts
import 'server-only';
import { prisma } from '@/lib/prisma';

export type PostView = {
  id: number;
  slug: string;
  title: string;
  body: string;
  authorName: string;
};

export async function getPost(slug: string): Promise<PostView | null> {
  const post = await prisma.post.findUnique({
    where: { slug },
    select: {
      id: true,
      slug: true,
      title: true,
      body: true,
      author: { select: { name: true } },
    },
  });
  if (!post) return null;
  return {
    id: post.id,
    slug: post.slug,
    title: post.title,
    body: post.body,
    authorName: post.author.name,
  };
}

Two habits matter here. First, select asks the database for only the columns you need, so a sensitive column such as a password hash is never even loaded. Second, the function returns a plain object of type PostView, not the ORM's own row type. The UI depends on a shape you control, so you can change the database schema without touching every component.

Create the Prisma client once and reuse it (lib/prisma.ts usually stores it on globalThis in development). Otherwise the dev server's hot reloading opens a new connection pool on every edit.

The same function with Drizzle

Drizzle is a lighter, SQL-flavored alternative. The calls read like a query, and the schema is written in TypeScript:

TSX
// lib/data/posts.ts (Drizzle version)
import 'server-only';
import { eq } from 'drizzle-orm';
import { db } from '@/db';
import { posts, users } from '@/db/schema';

export async function getPost(slug: string) {
  const [row] = await db
    .select({
      id: posts.id,
      slug: posts.slug,
      title: posts.title,
      body: posts.body,
      authorName: users.name,
    })
    .from(posts)
    .innerJoin(users, eq(posts.authorId, users.id))
    .where(eq(posts.slug, slug))
    .limit(1);
  return row ?? null;
}

The page that uses either version is identical, which is the point of the layer:

TSX
// app/blog/[slug]/page.tsx
import { notFound } from 'next/navigation';
import { getPost } from '@/lib/data/posts';

export default async function PostPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const post = await getPost(slug);
  if (!post) notFound();
  return (
    <article>
      <h1>{post.title}</h1>
      <p>By {post.authorName}</p>
      <div>{post.body}</div>
    </article>
  );
}

Prisma and Drizzle need a real database and a Node.js server, so they cannot run on this site. The live examples below use an in-memory array as a stand-in "database" and follow the same pattern: queries behind functions, DTOs on the way out.

DTOs: return only what the UI may see

A data transfer object (DTO) is a plain object built specially for the caller. It is how you stop leaking. Consider a user row with email, passwordHash and role. A public profile page needs the name only. If the DAL returns the whole row, any component can pass user as a prop to a Client Component, and that prop is serialized into the page for the browser to read. The password hash would travel with it.

Instead, give each audience its own function and shape: getPublicProfile(id) returns { name }, while getAccountSettings() returns { name, email } only after checking that the visitor is that user. Access checks belong in the layer too, so no caller can forget them. The security side of this is the subject of Authorization and Data Security.

Deduplicating with React cache

Layouts and pages render separately, and several components on one page often need the same record: the header wants the current user, the page wants the current user, the sidebar wants the current user. Passing props down every level is awkward, and querying three times is wasteful.

React's cache function wraps a DAL function so that, during one server render, calls with the same arguments run once and share the result:

TSX
import 'server-only';
import { cache } from 'react';

export const getUser = cache(async (id: number) => {
  return prisma.user.findUnique({ where: { id }, select: { id: true, name: true } });
});

Now any component can call getUser(1) freely. The memoization lasts only for the current request, so the next visitor triggers a fresh query. That is different from cross-request caching, which you will meet in The use cache Directive and Cache Components. Also note that fetch calls with the same URL and options are deduplicated for you automatically in the same way, but ORM and database calls are not, so wrap them with cache. The first example builds a miniature of this layer.

Node.js A tiny data access layer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Three components asked for the user, but the database was queried once. The password hash never left the layer, and the next request started with an empty memo, just like React's request-scoped cache.

Avoiding waterfalls

A waterfall happens when requests that could run side by side run one after another. Each await pauses the function, so this code takes the sum of the three delays:

TSX
const user = await getUser(id);
const posts = await getPosts(id);        // does not need user, still waits
const followers = await getFollowers(id); // does not need posts, still waits

Only a request that truly needs the previous result should wait for it. Start independent requests together and await them as a group:

TSX
const [user, posts, followers] = await Promise.all([
  getUser(id),
  getPosts(id),
  getFollowers(id),
]);

Waterfalls also appear across components. If a parent awaits its data before rendering a child, and the child then awaits its own, the child's request starts late. Two cures help. Start the child's request early (a preload function that calls the query without awaiting, sometimes placed in the parent), or wrap slow parts in Suspense so the rest of the page does not wait, which is the topic of Streaming with Suspense. The second example measures the difference.

Node.js Waterfall versus parallel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The waterfall takes about three times as long as the parallel version. The dependent version sits in between: one unavoidable wait, then two requests in parallel. Reading a request chain and asking "does this really need that?" is one of the most valuable performance habits in a server-rendered app.

A short checklist

  • Keep every database call in functions under lib/data, each file starting with import 'server-only'.
  • Select only the columns you need and return DTOs, never raw rows.
  • Put access checks inside the layer, not in each page.
  • Wrap shared reads in cache so one render queries once.
  • Use Promise.all for independent requests, and look for waterfalls between parent and child components.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main benefit of a data access layer?

    A DAL centralizes database code so queries are reused, sensitive fields are filtered once and checks cannot be forgotten.
  2. 2. Why return a DTO instead of the raw database row?

    Props passed to Client Components are serialized into the page. Returning a purpose-built object keeps secrets and unneeded fields out.
  3. 3. What does React's cache function do for a DAL function?

    cache memoizes per request. The next visitor's render starts fresh, unlike cross-request caching with use cache.
  4. 4. Which code avoids a waterfall for three independent queries?

    Promise.all starts all three right away, so the total time is about the slowest query instead of the sum.

Summary

  • A data access layer puts all database code in server-only functions that components call, instead of scattering ORM calls through pages.
  • Prisma and Drizzle both fit the pattern: use select to load only needed columns and return plain objects.
  • DTOs and access checks inside the layer keep secrets out of props and make authorization hard to forget.
  • React's cache deduplicates calls with the same arguments within one render; fetch GET requests are already deduplicated that way.
  • Waterfalls come from sequential awaits and from parent-child fetching: use Promise.all, preloading and Suspense.

Next: SSG, SSR, ISR and Streaming Compared