Fetching from a Database

No API Needed

If your Next.js app owns the database, query it directly from Server Components through an ORM such as Prisma or Drizzle. (Database setup is in the Advance level.)

lib/products.ts

import 'server-only';
import { prisma } from '@/lib/prisma';

export async function getProductsByCategory(category: string, page = 1) {
  const take = 20;
  return prisma.product.findMany({
    where: { category: { slug: category }, stock: { gt: 0 } },
    orderBy: { createdAt: 'desc' },
    skip: (page - 1) * take,
    take,
    select: { id: true, name: true, price: true, imageUrl: true },
  });
}
// app/category/[slug]/page.tsx
import { getProductsByCategory } from '@/lib/products';

export default async function CategoryPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const products = await getProductsByCategory(slug);
  return <p>{products.length} products in {slug}</p>;
}

Database Calls and Caching

Note: ORM calls are not fetch, so the fetch cache does not apply. Pages using them are rendered per request unless you cache them with export const revalidate, unstable_cache or the 'use cache' directive (next module).