Software Studio
Back to Articles

Prisma Patterns for Next.js Applications

PrismaNext.jsDatabase
Cover illustration for Prisma Patterns for Next.js Applications

Prisma and Next.js are a powerful combination, but there are patterns you need to follow to avoid common pitfalls. These are the four we use on every App Router project.

1. Use a singleton Prisma client

The most important pattern is the singleton Prisma client.

In development, Next.js hot-reloading creates new module instances on every change. If each instance creates its own PrismaClient, each one opens its own connections. Without a singleton, you'll exhaust your database connection pool within minutes, and the first sign is usually a "too many connections" error that makes no sense for an app with one user.

The standard approach is to attach the Prisma client to the global object in development:

// lib/prisma.ts
import { PrismaClient } from "@prisma/client";

const globalForPrisma = globalThis as unknown as {
  prisma: PrismaClient | undefined;
};

export const prisma = globalForPrisma.prisma ?? new PrismaClient();

if (process.env.NODE_ENV !== "production") {
  globalForPrisma.prisma = prisma;
}

The global object survives hot reloads, so every reload reuses the same client. In production, a simple module-level instantiation works fine since the process is long-lived.

2. Read data in Server Components

With the App Router, you should leverage React Server Components for data fetching. Your Prisma queries run on the server by default, and no API routes are needed for simple reads.

// app/articles/page.tsx
import { prisma } from "@/lib/prisma";

export default async function ArticlesPage() {
  const articles = await prisma.article.findMany({
    where: { published: true },
    orderBy: { publishedAt: "desc" },
  });

  return (
    <ul>
      {articles.map((article) => (
        <li key={article.id}>{article.title}</li>
      ))}
    </ul>
  );
}

This simplifies your architecture significantly. There is no endpoint to write, no fetch call, and no loading state to manage for the initial render. The database client never reaches the browser either, because the component only runs on the server. I go into the model behind this in React Server Components: What Actually Changed.

3. Write data with Server Actions and Zod

For mutations, Server Actions provide a clean pattern. Define your action in a separate file with 'use server', validate input with Zod, and call Prisma directly.

// lib/actions/articles.ts
"use server";

import { z } from "zod";
import { revalidatePath } from "next/cache";
import { prisma } from "@/lib/prisma";

const ArticleInput = z.object({
  title: z.string().min(1),
  excerpt: z.string().min(1),
});

export async function createArticle(formData: FormData) {
  const input = ArticleInput.parse({
    title: formData.get("title"),
    excerpt: formData.get("excerpt"),
  });

  await prisma.article.create({ data: input });
  revalidatePath("/articles");
}

The type safety flows from your Prisma schema through your validation layer to your UI. If a field is renamed in the schema, the compiler points at every place that needs to change.

One thing to keep in mind: a Server Action is a public endpoint, even though it looks like a function call. Validate every input, and check that the caller is allowed to perform the action inside the action itself. Protecting the page that renders the form is not enough.

4. Wrap queries in thin data access functions

One pattern we've found valuable is creating thin data access functions that wrap Prisma queries. Rather than calling prisma.article.findMany() directly in your components, create a getPublishedArticles() function.

// lib/data.ts
import { prisma } from "@/lib/prisma";

export async function getPublishedArticles() {
  return prisma.article.findMany({
    where: { published: true },
    orderBy: { publishedAt: "desc" },
  });
}

This gives you a single place to add caching, filtering logic and error handling. The rule "only published articles are public" lives in one function, so a new page can't forget it. And if you later change how articles are stored or cached, the components calling the function don't need to know.

Putting it together

  • One client. A singleton stored on the global object in development.
  • Reads in Server Components. Query on the server and skip the API route.
  • Writes in Server Actions. Validate with Zod, authorize, then call Prisma.
  • Data access functions. A named function per query, so rules and caching have one home.

None of these is complicated. Together they keep a Next.js codebase easy to follow as it grows.

Once the patterns are in place, the next thing to look at is the queries themselves. PostgreSQL Performance: Queries That Scale covers indexes, pagination and the N+1 problem.