SkillPilotAI

Database in Next.js

Server Components and Server Actions already run on the server, so they can query the database directly, with no API route in between. This note sets up Prisma with PostgreSQL: schema, migration, a typed singleton client, reads, writes and the safety rules.

67.1 Problem: fetching your own API

  • The products page (a Server Component) calls fetch("/api/products").
  • npm run dev: GET /products 500 with TypeError: Failed to parse URL.
React (TSX)
type Product = { id: number; name: string }; export default async function ProductsPage() {  const res = await fetch("/api/products");  const list: Product[] = await res.json();  return (    <ul>      {list.map((p) => (        <li key={p.id}>{p.name}</li>      ))}    </ul>  );}
Output
$ npm run dev✓ Ready in 6.0sGET /products 500⨯ TypeError: Failed to parse URLfrom /api/products

67.2 Why the error?

  • A relative URL works in the browser because it knows the current domain; on the server there is no domain.
  • Even with a full URL it is an extra network request from the server to itself.
  • The Server Component is already on the server, so it can talk to the database directly.

67.3 What is an ORM

  • Raw SQL strings give no TypeScript types; a typo in a column name only shows up at runtime.
  • An ORM represents every table as a model in code, and every query result is typed.
  • Prisma: generates a client from a schema file. Drizzle: SQL-like TypeScript. This video uses Prisma.
PointRaw SQL stringPrismaDrizzle
TypesNoneGenerated from schemaInferred from TS table definitions
StyleSQL textMethod calls (findMany, create)SQL-like TypeScript
Typos caughtAt runtimeAt compile timeAt compile time
Injection riskHigh if you concatenate inputValues sent as parametersValues sent as parameters

67.4 Step 1: the schema file

  • generator: the generated client lives in app/generated/prisma.
  • datasource: PostgreSQL; in Prisma 7 the URL comes from an env variable in a separate config file.
  • model Product: id (auto-increment), name, price, inStock (default true).
Output
// prisma/schema.prismagenerator client {  provider = "prisma-client"  output   = "../app/generated/prisma"} datasource db {  provider = "postgresql"} model Product {  id      Int     @id @default(autoincrement())  name    String  price   Int  inStock Boolean @default(true)}

67.5 Step 2: migration + generate

  • migrate dev writes an SQL migration file in prisma/migrations and creates the Product table; commit it to Git.
  • generate reads the schema and builds the typed Prisma client; in Prisma 7 you run this step yourself.
Terminal
npx prisma migrate dev --name initnpx prisma generate
Output
$ npx prisma migrate dev --name initApplying migration `20261106094958_init`prisma/migrations/  └─ 20261106094958_init/    └─ migration.sqlYour database is now in sync with your schema. $ npx prisma generate✔ Generated Prisma Client (7.10.1)to ./app/generated/prisma in 161ms

67.6 Step 3: the Prisma client (singleton)

  • lib/db.ts creates the client with the PostgreSQL adapter and DATABASE_URL.
  • The client is saved on globalThis because in development the module reloads on every save and new clients would use up connections.
  • import "server-only" makes sure this file never reaches the browser bundle.
TypeScript
// lib/db.tsimport "server-only";import { PrismaPg } from "@prisma/adapter-pg";import { PrismaClient } from  "@/app/generated/prisma/client"; const adapter = new PrismaPg({  connectionString: process.env.DATABASE_URL,});const g = globalThis as {  prisma?: PrismaClient;};export const db =  g.prisma ?? new PrismaClient({ adapter });if (process.env.NODE_ENV !== "production")  g.prisma = db;

67.7 Step 4: write the query

  • Same getProducts as the caching video, now with a real Prisma query.
  • findMany with where inStock, orderBy price asc, and select for just three columns; the result type matches automatically.
  • "use cache" + cacheTag("products") keep it cached and refreshable by tag.
TypeScript
// lib/products.tsimport { cacheTag } from "next/cache";import { db } from "./db"; export async function getProducts() {  "use cache";  cacheTag("products");  return db.product.findMany({    where: { inStock: true },    orderBy: { price: "asc" },    select: {      id: true, name: true, price: true,    },  });}

67.8 Page: a Server Component

  • No API route and no useEffect: the page awaits getProducts and renders name and price.
  • In-stock products show up ordered by price.
React (TSX)
// app/products/page.tsximport { getProducts } from "@/lib/products";import { AddForm } from "./AddForm";export default async function ProductsPage() {  const products = await getProducts();  return (    <main>      <ul>        {products.map((p) => (          <li key={p.id}>{p.name}: ₹{p.price}</li>        ))}      </ul>      <AddForm />    </main>  );}
Output
Cotton T-shirt: ₹499Running Shoes: ₹999[input] Name[input] Price[button] Add
From request to HTML
  1. 1.Request comes in, the Server Component runs on the server

  2. 2.It calls a typed Prisma method (db.product.findMany)

  3. 3.Prisma builds the SQL and fetches rows from PostgreSQL

  4. 4.Page goes to the browser as ready HTML

  5. 5.The database password never reaches the browser

67.9 Insert: a Server Action

  • AddForm calls addProduct, which reads name and price and runs db.product.create.
  • updateTag("products") refreshes the cached list, so Steel Bottle shows up immediately.
TypeScript
"use server";import { updateTag } from "next/cache";import { db } from "@/lib/db"; export async function addProduct(  form: FormData,) {  const name = String(form.get("name"));  const price = Number(form.get("price"));  await db.product.create({    data: { name, price },  });  updateTag("products");}
Output
(add "Steel Bottle", 349)Steel Bottle: ₹349Cotton T-shirt: ₹499Running Shoes: ₹999[input] Name[input] Price[button] Add
Write path
  1. 1.User submits AddForm

  2. 2.addProduct runs on the server

  3. 3.db.product.create inserts a row in PostgreSQL

  4. 4.updateTag("products") expires the cached list

  5. 5.Page re-renders with Steel Bottle first (cheapest)

67.10 Checkpoint: db in a Client Component?

  • Importing db into a "use client" file and querying in useEffect fails the build: lib/db.ts imports server-only.
  • Good: the browser should never have the database password. Load data on the server and pass it down as props.
React (TSX)
"use client";import { useEffect, useState } from "react";import { db } from "@/lib/db"; export function ProductList() {  const [count, setCount] = useState(0);  useEffect(() => {    db.product.count().then(setCount);  }, []);  return <p>{count} products</p>;}
Output
$ npm run build./lib/db.ts:1:1Error: 'server-only' cannot be importedfrom a Client Component moduleIt should only be used from aServer Component.

67.11 Common mistakes

  • SQL injection: putting user input directly inside a raw SQL string; a quote in the input becomes part of the SQL and the table can be leaked or deleted.
  • Fix: use Prisma methods like findMany, which always send the value as a parameter.
  • Myth: you must build an API route to use a database. Server Components and Actions read and write directly; build a Route Handler only for external clients (mobile app, webhook).
TypeScript
// Wrong: user input inside the SQL stringimport { db } from "@/lib/db"; export async function search(q: string) {  return db.$queryRawUnsafe(    `SELECT * FROM "Product"     WHERE name = '${q}'`,  );}
TypeScript
// Right: value goes as a parameterimport { db } from "@/lib/db"; export async function search(q: string) {  return db.product.findMany({    where: { name: { contains: q } },  });}

67.12 Best practices

  • Keep all DB code in lib/db.ts and import server-only in it.
  • Never prefix DATABASE_URL with NEXT_PUBLIC_, or it ends up in the browser bundle.
  • Commit migrations to Git and run prisma migrate deploy in production.
  • Select only the columns you need.
  • Add Zod validation and an auth check in every action.

67.13 Interview tips

  • Server Components and Server Actions run on the server, so they query the database directly.
  • Use an ORM like Prisma or Drizzle; in Prisma the schema generates the migration and a typed client.
  • Keep the client as a singleton (globalThis) to avoid exhausting connections during dev reloads.
  • DB code stays server-only; reads are cached with tags, writes are followed by updateTag.
  • Never build SQL by string concatenation of user input.