Using the Database Client
How to query PostgreSQL via the Prisma v7 client in server components, API routes, and multi-tenant contexts.
@nebutra/db exports two functions, not a db singleton: getSystemDb() (no tenant scoping —
for cross-tenant admin/background work) and getTenantDb(tenantId) (RLS-scoped — see below).
Always import from this package — never instantiate PrismaClient directly in application code.
export { Prisma } from "#prisma-client"; // the generated client's own Prisma namespace
export { getSystemDb, getTenantDb, type PrismaClient } from "./client";Server Component queries
Fetch data directly in React Server Components. No API layer is needed for internal data access.
import { getSystemDb } from "@nebutra/db";
export default async function ProjectsPage() {
const db = getSystemDb();
const projects = await db.project.findMany({
orderBy: { createdAt: "desc" },
select: {
id: true,
name: true,
createdAt: true,
_count: { select: { members: true } },
},
});
return <ProjectList projects={projects} />;
}Server Components run on the server, so database access is safe. Never import @nebutra/db in Client Components ("use client" files) — the database credentials would be exposed to the browser.
Multi-tenant queries
getTenantDb(tenantId) from @nebutra/db is already the RLS-scoped client — no separate withRls
wrapper needed on top of it (that helper lives in @nebutra/tenant for wrapping a client you
already have; getTenantDb does the same thing as its own entry point).
import { getTenantDb } from "@nebutra/db";
import { getCurrentTenant } from "@nebutra/tenant";
export default async function ProjectsPage() {
const tenant = getCurrentTenant();
const db = getTenantDb(tenant.id);
// Only returns projects belonging to the current tenant
const projects = await db.project.findMany({
orderBy: { createdAt: "desc" },
});
return <ProjectList projects={projects} />;
}Always use getTenantDb(tenantId) (or getSystemDb() wrapped with withRls if you already hold
a system client) for any query that touches tenant-owned data. getSystemDb() alone returns data
across ALL tenants.
Client-side data fetching
Client Components must never import @nebutra/db. Fetch data through your API routes instead:
"use client";
import { useEffect, useState } from "react";
export function useProjects() {
const [projects, setProjects] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch("/api/projects")
.then((res) => res.json())
.then((data) => {
setProjects(data.data);
setLoading(false);
});
}, []);
return { projects, loading };
}import { getTenantDb } from "@nebutra/db";
import { getCurrentTenant } from "@nebutra/tenant";
import { NextResponse } from "next/server";
export async function GET() {
const tenant = getCurrentTenant();
const db = getTenantDb(tenant.id);
const projects = await db.project.findMany({
orderBy: { createdAt: "desc" },
});
return NextResponse.json(projects);
}Transactions
Use Prisma interactive transactions when multiple writes must succeed or fail together:
import { getSystemDb } from "@nebutra/db";
async function createOrganizationWithOwner(name: string, userId: string) {
const db = getSystemDb();
return db.$transaction(async (tx) => {
const org = await tx.organization.create({
data: { name },
});
await tx.membership.create({
data: {
organizationId: org.id,
userId,
role: "owner",
},
});
await tx.auditLog.create({
data: {
organizationId: org.id,
action: "organization.created",
actorId: userId,
},
});
return org;
});
}Error handling
Prisma throws typed errors. Handle them explicitly to return meaningful responses:
import { Prisma } from "@nebutra/db";
export function handlePrismaError(error: unknown): never {
if (error instanceof Prisma.PrismaClientKnownRequestError) {
switch (error.code) {
case "P2002":
// Unique constraint violation
throw new Error(`A record with this value already exists. Field: ${error.meta?.target}`);
case "P2025":
// Record not found
throw new Error("The requested record does not exist.");
case "P2003":
// Foreign key constraint failed
throw new Error("This operation references a record that does not exist.");
default:
throw new Error(`Database error: ${error.code}`);
}
}
if (error instanceof Prisma.PrismaClientValidationError) {
throw new Error("Invalid data provided to the database query.");
}
throw error;
}Common Prisma error codes:
| Code | Meaning |
|---|---|
P2002 | Unique constraint violation |
P2003 | Foreign key constraint failed |
P2025 | Record not found (findUniqueOrThrow, update, delete) |
P2016 | Query interpretation error |
P1001 | Cannot reach database server |
P1002 | Database server timeout |
Typed queries
Prisma v7 generates full TypeScript types for every model and query. Use the generated types directly:
import type { Prisma } from "@nebutra/db";
// Infer the return type of a specific query shape
type ProjectWithCount = Prisma.ProjectGetPayload<{
include: {
_count: { select: { members: true } };
};
}>;
// Use in component props
interface ProjectCardProps {
project: ProjectWithCount;
}Use Prisma.XxxGetPayload to derive precise types from your query's select or include shape. This avoids maintaining manual interface definitions that can drift from the schema.
How is this guide?
Last updated on