Next.js Zero to Advanced #7: Fetching Data from the Database
In Part 6 we set up a PostgreSQL database through Prisma: User, Product, and Order tables, plus six sample products from the seed script. But DigiStore's pages still read the in-memory array in lib/products.ts. In Part 7 we connect the two: Server Components query the database directly, the product list gets search, a category filter, and pagination through searchParams, the detail page uses findUnique, and we add caching plus loading, empty, and error states.
By the end of this part every store page shows real data from PostgreSQL, and you will understand when data is fetched at build time, when it is cached, and when it is fetched per request.
Preparation: Cache Components and server-only
Check next.config.ts
Next.js 16 has a new caching model called Cache Components. If you picked the recommended create-next-app defaults in Part 1, it is already on. Open next.config.ts and make sure both options below are present. If they are not, add them and restart npm run dev.
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: true,
// images.remotePatterns from Part 4 stays here
}
export default nextConfigWith Cache Components, Next.js tries to render as much of each page as possible at build time (the static shell). Anything that needs per-request data, such as reading searchParams or an uncached database query, must be wrapped in <Suspense> or cached with 'use cache'. If you forget, the dev overlay shows a blocking-route insight pointing at the component. The rule helps: it forces you to decide on purpose which data is static and which is dynamic.
Protect server code with server-only
Files that import Prisma must never end up in the browser bundle. The server-only package makes the build fail if such a file is accidentally imported from a Client Component (we covered the server/client boundary in Part 3).
npm install server-onlyClient-safe category labels
Category labels are needed on both the server and the client (the search form now, the admin form in Part 8). So we put them in lib/format.ts, which never touches the database, below formatRupiah from Part 4.
// lib/format.ts (formatRupiah from Part 4 stays above)
export const CATEGORY_LABELS = {
EBOOK: 'E-book',
SOURCE_CODE: 'Source Code',
TEMPLATE: 'Template',
} as const
export type CategoryValue = keyof typeof CATEGORY_LABELS
export function isCategory(value: string): value is CategoryValue {
return Object.hasOwn(CATEGORY_LABELS, value)
}
export function formatCategory(category: CategoryValue): string {
return CATEGORY_LABELS[category]
}isCategory is a type guard: once a value passes it, TypeScript knows it is one of EBOOK, SOURCE_CODE, or TEMPLATE, exactly matching the Category enum in the Prisma schema.
Replacing lib/products.ts with Prisma Queries
Delete the old contents of lib/products.ts (the in-memory array from Part 2) and replace them with the version below. We split it into three pieces to keep it readable.
Piece 1: select, types, and query parsing
// lib/products.ts
import 'server-only'
import { cacheLife, cacheTag } from 'next/cache'
import type { Prisma } from '@prisma/client'
import { prisma } from '@/lib/prisma'
import { isCategory, type CategoryValue } from '@/lib/format'
export const PAGE_SIZE = 4
// Only the columns a ProductCard needs
const productCardSelect = {
id: true,
slug: true,
title: true,
price: true,
category: true,
imageUrl: true,
} satisfies Prisma.ProductSelect
export type ProductCardData = Prisma.ProductGetPayload<{
select: typeof productCardSelect
}>
export type ProductQuery = {
q: string
category: CategoryValue | null
page: number
}
type RawParams = Record<string, string | string[] | undefined>
// Query strings are untrusted input: normalise them before using them
export function parseProductQuery(params: RawParams): ProductQuery {
const first = (value: string | string[] | undefined) =>
Array.isArray(value) ? value[0] : value
const q = (first(params.q) ?? '').trim().slice(0, 100)
const rawCategory = first(params.category) ?? ''
const page = Number.parseInt(first(params.page) ?? '1', 10)
return {
q,
category: isCategory(rawCategory) ? rawCategory : null,
page: Number.isInteger(page) && page > 0 ? Math.min(page, 1000) : 1,
}
}Two important ideas live here. First, select only the columns you need. A product card does not need the long description, createdAt, or the orders relation. Fetching just enough keeps queries light and stops unnecessary data from reaching the client. This habit becomes critical in Part 10, where we must never send passwordHash to the browser. Prisma.ProductGetPayload then derives the TypeScript type from that same select, so the type and the query can never drift apart.
Second, the query string is untrusted input. Anyone can type ?page=-5 or ?category=HACK into the address bar. parseProductQuery normalises everything: the search text is capped at 100 characters, unknown categories are ignored, and odd page numbers fall back to 1.
Piece 2: product list with search and pagination
export async function getProducts({ q, category, page }: ProductQuery) {
'use cache'
cacheLife('hours')
cacheTag('products')
const where: Prisma.ProductWhereInput = {
published: true,
...(category ? { category } : {}),
...(q
? {
OR: [
{ title: { contains: q, mode: 'insensitive' } },
{ description: { contains: q, mode: 'insensitive' } },
],
}
: {}),
}
const [items, total] = await prisma.$transaction([
prisma.product.findMany({
where,
select: productCardSelect,
orderBy: { createdAt: 'desc' },
skip: (page - 1) * PAGE_SIZE,
take: PAGE_SIZE,
}),
prisma.product.count({ where }),
])
return {
items,
total,
totalPages: Math.max(1, Math.ceil(total / PAGE_SIZE)),
}
}containswithmode: 'insensitive'gives case-insensitive search (on PostgreSQL Prisma usesILIKE). Prisma always uses query parameters, so user input is safe from SQL injection.skipandtakeimplement offset pagination: page 2 withPAGE_SIZE = 4means skip 4 rows, take 4 rows. We use 4 so pagination is visible right away: the Part 6 seed has 5 published products and 1 draft.prisma.$transaction([...])runsfindManyandcountin one transaction, so the total and the page contents stay consistent.published: trueensures products an admin has unpublished never show up in the store.
Piece 3: featured products and the detail query
export async function getFeaturedProducts() {
'use cache'
cacheLife('hours')
cacheTag('products')
return prisma.product.findMany({
where: { published: true },
select: productCardSelect,
orderBy: { createdAt: 'desc' },
take: 3,
})
}
export async function getProductBySlug(slug: string) {
'use cache'
cacheLife('hours')
cacheTag('products')
return prisma.product.findUnique({
where: { slug, published: true },
select: { ...productCardSelect, description: true },
})
}Since Prisma 5, findUnique accepts extra filters next to the unique column, so where: { slug, published: true } is valid. If the product does not exist or is unpublished, the result is null.
What do use cache, cacheLife, and cacheTag mean?
All three functions start with the 'use cache' directive. Next.js stores the function's result, and its arguments (such as q, category, page) automatically become part of the cache key. A search for "next" on page 1 has its own cache entry, separate from category TEMPLATE on page 2.
| API | Purpose |
|---|---|
'use cache' | Marks a function whose result may be cached. Arguments and return values must be serializable (plain objects from Prisma are fine). |
cacheLife('hours') | Cache lifetime. The hours profile: stale after 5 minutes in the browser, revalidated on the server every hour, expires after 1 day. |
cacheTag('products') | Labels the entry so it can be invalidated on demand. In Part 8 we call updateTag('products') after an admin changes a product. |
This cache holds public catalog data that is identical for every visitor. Never use plain
'use cache'for data that belongs to one user (such as orders in Part 10), because the result could be shared with other users.
Updating ProductCard
Product data now comes from Prisma, so the ProductCard from Part 4 should accept ProductCardData. If your markup differs, the only required change is the props type. Note that imageUrl may now be null, so we render a placeholder.
// components/ProductCard.tsx
import Image from 'next/image'
import Link from 'next/link'
import { formatCategory, formatRupiah } from '@/lib/format'
import type { ProductCardData } from '@/lib/products'
export function ProductCard({ product }: { product: ProductCardData }) {
return (
<Link
href={`/products/${product.slug}`}
className="group block rounded-xl border border-gray-200 p-4 transition hover:shadow-md"
>
{product.imageUrl ? (
<Image
src={product.imageUrl}
alt={product.title}
width={400}
height={300}
className="aspect-[4/3] w-full rounded-lg object-cover"
/>
) : (
<div className="flex aspect-[4/3] items-center justify-center rounded-lg bg-gray-100 text-sm text-gray-500">
Tidak ada gambar
</div>
)}
<p className="mt-3 text-xs font-medium uppercase text-gray-500">
{formatCategory(product.category)}
</p>
<h3 className="mt-1 font-semibold group-hover:underline">{product.title}</h3>
<p className="mt-2 font-bold">{formatRupiah(product.price)}</p>
</Link>
)
}import type only brings in types and is erased at compile time, so it is safe even though lib/products.ts is marked server-only.
The Product List Page: searchParams, Search, and Pagination
In Next.js 16, searchParams is a Promise, just like params from Part 2. Because its value is only known at request time, we read it inside a component wrapped in <Suspense>. The page heading and skeleton ship instantly from the static shell, and the results stream in.
// app/products/page.tsx
import { Suspense } from 'react'
import Form from 'next/form'
import Link from 'next/link'
import { ProductCard } from '@/components/ProductCard'
import { Button } from '@/components/ui/Button'
import { CATEGORY_LABELS } from '@/lib/format'
import { getProducts, parseProductQuery, type ProductQuery } from '@/lib/products'
type SearchParams = Promise<Record<string, string | string[] | undefined>>
export default function ProductsPage({ searchParams }: { searchParams: SearchParams }) {
return (
<main className="mx-auto max-w-6xl px-4 py-8">
<h1 className="text-2xl font-bold">Semua Produk</h1>
<Suspense fallback={<ProductGridSkeleton />}>
<ProductResults searchParams={searchParams} />
</Suspense>
</main>
)
}
async function ProductResults({ searchParams }: { searchParams: SearchParams }) {
const query = parseProductQuery(await searchParams)
const { items, total, totalPages } = await getProducts(query)
return (
<>
<SearchForm query={query} />
<p className="mt-4 text-sm text-gray-600" aria-live="polite">
{total} produk ditemukan
</p>
{items.length === 0 ? (
<div className="mt-8 rounded-xl border border-dashed p-8 text-center">
<p className="font-medium">Produk tidak ditemukan.</p>
<Link href="/products" className="mt-2 inline-block underline">
Lihat semua produk
</Link>
</div>
) : (
<div className="mt-6 grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
{items.map((product) => (
<ProductCard key={product.id} product={product} />
))}
</div>
)}
<Pagination query={query} totalPages={totalPages} />
</>
)
}Then add the supporting components to the same file:
// app/products/page.tsx (continued)
function SearchForm({ query }: { query: ProductQuery }) {
return (
<Form action="/products" className="mt-6 flex flex-col gap-3 sm:flex-row">
<label htmlFor="q" className="sr-only">Cari produk</label>
<input
id="q"
name="q"
type="search"
defaultValue={query.q}
placeholder="Cari e-book, source code, template..."
className="flex-1 rounded-lg border px-3 py-2"
/>
<label htmlFor="category" className="sr-only">Kategori</label>
<select
id="category"
name="category"
defaultValue={query.category ?? ''}
className="rounded-lg border px-3 py-2"
>
<option value="">Semua kategori</option>
{Object.entries(CATEGORY_LABELS).map(([value, label]) => (
<option key={value} value={value}>{label}</option>
))}
</select>
<Button type="submit">Cari</Button>
</Form>
)
}
function pageHref(query: ProductQuery, page: number) {
const params = new URLSearchParams()
if (query.q) params.set('q', query.q)
if (query.category) params.set('category', query.category)
if (page > 1) params.set('page', String(page))
const search = params.toString()
return search ? `/products?${search}` : '/products'
}
function Pagination({ query, totalPages }: { query: ProductQuery; totalPages: number }) {
if (totalPages <= 1) return null
return (
<nav aria-label="Navigasi halaman" className="mt-8 flex items-center justify-center gap-4">
{query.page > 1 && <Link href={pageHref(query, query.page - 1)}>← Sebelumnya</Link>}
<span className="text-sm text-gray-600">
Halaman {query.page} dari {totalPages}
</span>
{query.page < totalPages && <Link href={pageHref(query, query.page + 1)}>Berikutnya →</Link>}
</nav>
)
}
function ProductGridSkeleton() {
return (
<div
className="mt-6 grid gap-6 sm:grid-cols-2 lg:grid-cols-4"
aria-busy="true"
aria-label="Memuat produk"
>
{Array.from({ length: 4 }, (_, i) => (
<div key={i} className="h-64 animate-pulse rounded-xl bg-gray-100" />
))}
</div>
)
}A few notes:
Formfromnext/formwithaction="/products"behaves like a plain HTML GET form: the fields become the query string. The difference is that Next.js performs a client-side navigation instead of a full reload, and the form still works before JavaScript loads.pageHrefkeepsqandcategorywhen changing pages, so filters are not lost.- The empty state ("Produk tidak ditemukan") and the loading state (skeleton) are handled. We add the error state shortly.
aria-live="polite"makes screen readers announce the result count whenever the search changes.
The UI text stays in Indonesian because DigiStore targets Indonesian buyers. Try these URLs one by one:
http://localhost:3000/products
http://localhost:3000/products?q=next
http://localhost:3000/products?category=TEMPLATE
http://localhost:3000/products?page=2
http://localhost:3000/products?category=HACK&page=-5Result: the first URL shows the 4 newest products and a "Berikutnya →" (Next) link. ?q=next only shows products whose title or description contains "next", regardless of case. ?category=TEMPLATE only shows Template Landing Page, because Template Dashboard Admin is still a draft. ?page=2 shows the 1 remaining product. The last URL does not crash: the unknown category is ignored and the page falls back to 1.
The Detail Page with findUnique
// app/products/[slug]/page.tsx
import Image from 'next/image'
import { notFound } from 'next/navigation'
import { formatCategory, formatRupiah } from '@/lib/format'
import { getProductBySlug } from '@/lib/products'
export default async function ProductDetailPage({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
if (slug.length > 100) notFound()
const product = await getProductBySlug(slug)
if (!product) notFound()
return (
<main className="mx-auto grid max-w-5xl gap-8 px-4 py-8 md:grid-cols-2">
{product.imageUrl && (
<Image
src={product.imageUrl}
alt={product.title}
width={800}
height={600}
className="w-full rounded-xl object-cover"
/>
)}
<div>
<p className="text-sm uppercase text-gray-500">{formatCategory(product.category)}</p>
<h1 className="mt-1 text-3xl font-bold">{product.title}</h1>
<p className="mt-4 text-2xl font-semibold">{formatRupiah(product.price)}</p>
<p className="mt-6 whitespace-pre-line text-gray-700">{product.description}</p>
{/* AddToCartButton from Part 3 stays here */}
</div>
</main>
)
}The detail page awaits params at the top level, so the whole page depends on the request. To keep a fallback, add loading.tsx, which automatically wraps page.tsx in <Suspense>.
// app/products/[slug]/loading.tsx
export default function Loading() {
return (
<main className="mx-auto max-w-5xl px-4 py-8" aria-busy="true">
<div className="h-8 w-2/3 animate-pulse rounded bg-gray-100" />
<div className="mt-4 h-6 w-1/3 animate-pulse rounded bg-gray-100" />
<div className="mt-8 h-40 animate-pulse rounded-xl bg-gray-100" />
</main>
)
}If the slug is not found, notFound() renders the not-found.tsx you built in Part 2. The slug length check is a small defence so very long URLs do not create useless cache entries.
Optional: generateStaticParams
If you want detail pages prerendered at build time, add generateStaticParams:
// app/products/[slug]/page.tsx (optional)
import { prisma } from '@/lib/prisma'
export async function generateStaticParams() {
const products = await prisma.product.findMany({
where: { published: true },
select: { slug: true },
})
return products.map((product) => ({ slug: product.slug }))
}There are two consequences. With Cache Components the function must return at least one param; an empty array (for example, an unseeded database) fails the build. Also, npm run build now needs a database connection. For DigiStore you can skip it: detail pages are already fast because getProductBySlug is cached.
Featured Products on the Home Page
// app/page.tsx (only the product section changes)
import { ProductCard } from '@/components/ProductCard'
import { getFeaturedProducts } from '@/lib/products'
async function FeaturedProducts() {
const products = await getFeaturedProducts()
if (products.length === 0) {
return <p className="text-gray-600">Belum ada produk.</p>
}
return (
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
{products.map((product) => (
<ProductCard key={product.id} product={product} />
))}
</div>
)
}
// Inside HomePage's JSX:
// <h2 className="text-xl font-semibold">Produk Terbaru</h2>
// <FeaturedProducts />getFeaturedProducts does not depend on any request data, so Next.js runs it at build time and puts the result into the home page's static shell. The home page is served as fast as a static file. The trade-off: DATABASE_URL must be available during the build, which we handle when deploying in Part 12.
| Page | Rendering | Why |
|---|---|---|
/ | Static shell + cached data | Reads no request data |
/products | Static shell, results streamed | Reads searchParams |
/products/[slug] | Per request (loading.tsx fallback), cached data | Reads params |
Error State with error.tsx
What happens if PostgreSQL is down? The Prisma query throws. Without handling, users see the default error page. Create app/products/error.tsx:
// app/products/error.tsx
'use client' // Error boundaries must be Client Components
import { useEffect } from 'react'
import { Button } from '@/components/ui/Button'
export default function ProductsError({
error,
retry,
}: {
error: Error & { digest?: string }
retry: () => void
}) {
useEffect(() => {
console.error(error)
}, [error])
return (
<main className="mx-auto max-w-xl px-4 py-16 text-center" role="alert">
<h2 className="text-xl font-semibold">Gagal memuat produk</h2>
<p className="mt-2 text-gray-600">
Terjadi gangguan saat mengambil data. Silakan coba lagi.
</p>
<div className="mt-6">
<Button type="button" onClick={() => retry()}>
Coba lagi
</Button>
</div>
</main>
)
}Error boundaries must be Client Components. Note the retry prop: since Next.js 16.3 this is the recommended way to try again, because retry() re-fetches the data and re-renders the segment. The older reset() prop still exists, but it only clears the error state without re-fetching. In production, error.message from a Server Component is replaced with a generic message so sensitive details (like query contents) do not leak; use error.digest to match the server logs.
Try stopping the database (for example, docker stop on the container from Part 5) and open /products. Result: "Gagal memuat produk" (failed to load products) appears. Start the database again and click "Coba lagi" (try again); the products return without a full reload.
Common Mistakes
- Reading
searchParamswithout<Suspense>. The dev overlay shows a blocking-route insight. Moveawait searchParamsinto a child component wrapped in<Suspense>, or provideloading.tsx. - Forgetting to
awaitparams/searchParams. Both are Promises in Next.js 16. ReadingsearchParams.qdirectly givesundefined. - Using
parseInton query values without validation.?page=abcproducesNaN, andskip: NaNmakes Prisma throw. Always normalise URL input. - Fetching every column with
findMany()and noselect. Wasteful, and risky once the table grows sensitive columns. - Importing
lib/products.tsfrom a Client Component. Thanks toserver-only, the build fails with a clear message. Pass data down as props from a Server Component. - Using
'use cache'for per-user data. This cache is shared across all visitors; personal data must never go into it.
Exercises
- Add sorting with
?sort=price_asc/?sort=price_desc/?sort=newest. Validate the value inparseProductQueryand pass it toorderBy. - Render numbered page links (1, 2, 3, ...) in addition to Previous and Next, with
aria-current="page"on the active page. - On the detail page, show three "other products in the same category" using a new
'use cache'function that excludes the current product.
Summary
- Server Components can call Prisma directly; database credentials never reach the browser, and
server-onlyguards that boundary. searchParamsandparamsare Promises. Read them inside<Suspense>or on a page that hasloading.tsx.- URL input is validated and normalised before it reaches a query.
selectfetches only the needed columns, andPrisma.ProductGetPayloadderives the type from thatselect.'use cache'+cacheLife+cacheTagcache the catalog data. Theproductstag is what we invalidate in Part 8.- Loading state via
<Suspense>/loading.tsx, empty state via anitems.lengthcheck, error state viaerror.tsxwithretry().
The store now reads real data, but new products can only be added through the seed script or Prisma Studio. In Part 8 we build admin pages to create, edit, and delete products with Server Actions, zod validation, and useActionState.
Related articles
PostgreSQL Zero to Advanced #1: Introduction & Setup
Start the series by understanding what a relational database is, installing PostgreSQL locally, and getting comfortable with psql commands like \l, \c and \dt.
PHP Zero to Advanced #5: Arrays & Array Functions
Master PHP arrays: indexed and associative arrays, nested data, destructuring, and the essential functions array_map, array_filter, array_reduce, usort, and friends.
Ruby on Rails Zero to Advanced #5: Routing, Controllers & Views
Follow a request through Rails: define routes, use resources, read params in controllers, and render dynamic HTML with ERB views and partials.