Next.js Zero to Advanced #2: Routing, Layouts & Navigation
In Part 1 we created the DigiStore project and replaced the home page. Now it is time for DigiStore to get some real pages. In Part 2 we build a product list at /products, a detail page at /products/[slug], a navigation header shown on every page, a catalog sidebar using a nested layout, plus "not found" and loading screens. The data is still a simple in-memory array; the PostgreSQL database arrives in Parts 5β7.
File-based Routing Concepts
Folders become URLs
In the App Router you do not write a route list by hand. Folders inside app/ become URL segments, and a route becomes publicly accessible when it contains a page.tsx file.
| File | URL |
|---|---|
app/page.tsx | / |
app/products/page.tsx | /products |
app/products/[slug]/page.tsx | /products/ebook-belajar-nextjs, /products/source-code-kasir-nextjs, etc. |
A folder without page.tsx does not produce a page. That means you can keep supporting files inside app/ without worrying that they become URLs.
Special files
Besides page.tsx, a few file names have special roles. The ones we use in this part:
layout.tsx: UI that wraps pages and is shared. Layouts do not re-render when you navigate between pages, so their state is preserved.page.tsx: the UI unique to a route.loading.tsx: a temporary screen while the page content is being prepared.not-found.tsx: the screen shown when content is not found (404).
There is also error.tsx for handling errors, which we cover in Part 7 and Part 11.
Temporary Product Data
Until we have a database, we keep products in an array. Create a lib folder in the project root (next to app), then create lib/products.ts:
// lib/products.ts
export type Category = 'EBOOK' | 'SOURCE_CODE' | 'TEMPLATE'
export type Product = {
id: string
slug: string
title: string
description: string
price: number // in rupiah, no decimals
category: Category
imageUrl: string | null
published: boolean
}
export const categoryLabels: Record<Category, string> = {
EBOOK: 'E-book',
SOURCE_CODE: 'Source Code',
TEMPLATE: 'Template',
}
const products: Product[] = [
{
id: 'p1',
slug: 'ebook-belajar-nextjs',
title: 'E-book Belajar Next.js',
description: 'Panduan praktis membangun aplikasi web dengan Next.js.',
price: 99000,
category: 'EBOOK',
imageUrl: '/products/ebook-belajar-nextjs.jpg',
published: true,
},
{
id: 'p2',
slug: 'ebook-dasar-postgresql',
title: 'E-book Dasar PostgreSQL',
description: 'Belajar SQL dan desain tabel dari nol.',
price: 79000,
category: 'EBOOK',
imageUrl: null,
published: true,
},
{
id: 'p3',
slug: 'source-code-kasir-nextjs',
title: 'Source Code Aplikasi Kasir',
description: 'Aplikasi kasir sederhana dengan Next.js dan Prisma.',
price: 249000,
category: 'SOURCE_CODE',
imageUrl: null,
published: true,
},
{
id: 'p4',
slug: 'source-code-rest-api-starter',
title: 'REST API Starter',
description: 'Kerangka REST API dengan validasi dan autentikasi.',
price: 199000,
category: 'SOURCE_CODE',
imageUrl: null,
published: true,
},
{
id: 'p5',
slug: 'template-landing-page',
title: 'Template Landing Page',
description: 'Landing page responsif berbasis Tailwind CSS.',
price: 149000,
category: 'TEMPLATE',
imageUrl: null,
published: true,
},
{
id: 'p6',
slug: 'template-dashboard-admin',
title: 'Template Dashboard Admin',
description: 'Dashboard admin dengan tabel, grafik, dan form.',
price: 179000,
category: 'TEMPLATE',
imageUrl: null,
published: false,
},
]
export async function getProducts(): Promise<Product[]> {
return products.filter((product) => product.published)
}
export async function getProductBySlug(slug: string): Promise<Product | undefined> {
// Simulated database delay so loading.tsx is visible. Removed in Part 7.
await new Promise((resolve) => setTimeout(resolve, 800))
return products.find((product) => product.slug === slug && product.published)
}
A few notes:
- The
Productshape deliberately mirrors the database model we will create with Prisma in Part 6, so switching over later is smooth. - Prices are stored as whole rupiah integers (
99000), not decimals. This avoids rounding problems with fractional numbers. - The functions are
asynceven though the data lives in memory, because database queries will be async too. Pages that call them will barely need to change. - Product
p6is not published yet (published: false), so it must not appear in the list or be reachable by URL.
The product titles and UI text stay in Indonesian because DigiStore is an Indonesian store.
Root Layout and Navigation
Adding a header to app/layout.tsx
The navigation header should appear on every page, so it belongs in the root layout. Open app/layout.tsx. Leave the default font imports and metadata as they are (we tidy them up in Part 4); change the RootLayout component so the file looks like this:
// app/layout.tsx
import type { Metadata } from 'next'
import { Geist, Geist_Mono } from 'next/font/google'
import Link from 'next/link'
import './globals.css'
const geistSans = Geist({
variable: '--font-geist-sans',
subsets: ['latin'],
})
const geistMono = Geist_Mono({
variable: '--font-geist-mono',
subsets: ['latin'],
})
export const metadata: Metadata = {
title: 'Create Next App',
description: 'Generated by create next app',
}
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html lang="id">
<body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
<header className="border-b">
<nav className="mx-auto flex max-w-5xl items-center gap-6 p-4">
<Link href="/" className="text-lg font-bold">
DigiStore
</Link>
<Link href="/products" className="hover:underline">
Produk
</Link>
</nav>
</header>
<main className="mx-auto max-w-5xl p-4">{children}</main>
<footer className="mx-auto max-w-5xl p-4 text-sm text-gray-500">
DigiStore: proyek belajar Next.js di FullstackNotes
</footer>
</body>
</html>
)
}
The children prop contains the currently active page. The layout decides where that page goes, in this case inside <main>, between the header and the footer.
Why Link and not <a>?
The <Link> component from next/link renders an ordinary <a> tag, but with two advantages:
- Client-side navigation: when clicked, the browser does not reload the whole page. Only the parts that change are replaced, while the layout (header, footer) stays in place.
- Prefetching: Next.js fetches the destination route ahead of time when the link is visible on screen, so navigation feels instant.
Use <Link> for all internal navigation. A plain <a> tag is still fine for links to external sites.
Adjusting the home page
Because the root layout now wraps pages in <main>, remove <main> from app/page.tsx so there are not two main elements. While we are at it, add a button to the catalog:
// app/page.tsx
import Link from 'next/link'
export default function HomePage() {
return (
<section className="py-8">
<h1 className="text-3xl font-bold">Selamat datang di DigiStore</h1>
<p className="mt-4 text-lg">
Toko produk digital: e-book, source code, dan template siap pakai.
</p>
<Link
href="/products"
className="mt-6 inline-block rounded bg-blue-600 px-4 py-2 text-white hover:bg-blue-700"
>
Lihat produk
</Link>
</section>
)
}
The Product List Page
Create the app/products folder, then the file app/products/page.tsx:
// app/products/page.tsx
import Link from 'next/link'
import { categoryLabels, getProducts } from '@/lib/products'
export default async function ProductsPage() {
const products = await getProducts()
if (products.length === 0) {
return <p>Belum ada produk yang dijual.</p>
}
return (
<div>
<h1 className="text-2xl font-bold">Semua Produk</h1>
<ul className="mt-4 space-y-3">
{products.map((product) => (
<li key={product.id} className="rounded border p-4">
<Link
href={`/products/${product.slug}`}
className="font-semibold hover:underline"
>
{product.title}
</Link>
<p className="text-sm text-gray-600">
{categoryLabels[product.category]} Β· Rp{' '}
{product.price.toLocaleString('id-ID')}
</p>
</li>
))}
</ul>
</div>
)
}
Notice that a page component can be an async function that awaits data directly. This works because pages are Server Components (details in Part 3). We also handle the empty state: if the array is empty, we show a clear message instead of a blank page.
For now, prices are formatted with toLocaleString('id-ID'). In Part 4 we write a tidier formatRupiah function.
Open http://localhost:3000/products. Result: five products are listed (the sixth is not, because it is unpublished), each with its category and price, for example "E-book Β· Rp 99.000".
Nested Layout: The Catalog Sidebar
Layouts can be nested. A layout inside the app/products folder only wraps pages under /products, and it is itself wrapped by the root layout. Create app/products/layout.tsx:
// app/products/layout.tsx
import Link from 'next/link'
import { getProducts } from '@/lib/products'
export default async function ProductsLayout({
children,
}: {
children: React.ReactNode
}) {
const products = await getProducts()
return (
<div className="grid gap-8 md:grid-cols-[220px_1fr]">
<aside>
<p className="mb-2 text-sm font-semibold uppercase text-gray-500">Katalog</p>
<ul className="space-y-1 text-sm">
<li>
<Link href="/products" className="hover:underline">
Semua produk
</Link>
</li>
{products.map((product) => (
<li key={product.id}>
<Link href={`/products/${product.slug}`} className="hover:underline">
{product.title}
</Link>
</li>
))}
</ul>
</aside>
<section>{children}</section>
</div>
)
}
The wrapping order is: root layout β products layout β page. When you navigate from /products to a detail page, the sidebar is not re-rendered; only the children part changes. A nested layout must not contain <html> or <body> tags; those belong only in the root layout.
Dynamic Route: The Product Detail Page
Creating the [slug] segment
We cannot create a folder for every product. The solution is a dynamic segment: a folder name wrapped in square brackets, such as [slug]. The part of the URL in that position is passed to the page as params. Create app/products/[slug]/page.tsx:
// app/products/[slug]/page.tsx
import Link from 'next/link'
import { notFound } from 'next/navigation'
import { categoryLabels, getProductBySlug } from '@/lib/products'
export default async function ProductDetailPage({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
const product = await getProductBySlug(slug)
if (!product) {
notFound()
}
return (
<article>
<p className="text-sm text-gray-500">{categoryLabels[product.category]}</p>
<h1 className="text-2xl font-bold">{product.title}</h1>
<p className="mt-2 text-xl">Rp {product.price.toLocaleString('id-ID')}</p>
<p className="mt-4 leading-relaxed">{product.description}</p>
<Link href="/products" className="mt-6 inline-block text-blue-600 hover:underline">
β Kembali ke daftar produk
</Link>
</article>
)
}
params is a Promise
This is an important change in recent Next.js versions: params is not a plain object but a Promise. That is why its type is Promise<{ slug: string }> and we must write const { slug } = await params. Reading params.slug directly (the old-tutorial style) will not work.
| URL | slug value |
|---|---|
/products/ebook-belajar-nextjs | 'ebook-belajar-nextjs' |
/products/source-code-kasir-nextjs | 'source-code-kasir-nextjs' |
/products/anything | 'anything' (no such product β 404) |
Next.js also provides a global PageProps type helper, generated automatically while next dev runs. The following is equivalent:
export default async function ProductDetailPage(props: PageProps<'/products/[slug]'>) {
const { slug } = await props.params
// ...
}
In this series we use explicit types because they are easier for beginners to follow, but either is fine.
Never trust values from the URL
The slug value is typed by the user in the address bar, so it can contain anything. We do not use it raw; we only use it to look up a product. If nothing matches (or the product is unpublished), we stop with notFound(). This "validate external input" habit becomes even more important once we use a database and forms.
notFound() and not-found.tsx
A product-specific 404 page
The notFound() function from next/navigation throws a special signal that stops rendering and shows the nearest 404 UI. You do not need return notFound(); calling it is enough, and TypeScript understands that after that line product is defined. Create app/products/[slug]/not-found.tsx:
// app/products/[slug]/not-found.tsx
import Link from 'next/link'
export default function ProductNotFound() {
return (
<div>
<h1 className="text-2xl font-bold">Produk tidak ditemukan</h1>
<p className="mt-2">Produk yang Anda cari tidak ada atau sudah tidak dijual.</p>
<Link href="/products" className="mt-4 inline-block text-blue-600 hover:underline">
Lihat semua produk
</Link>
</div>
)
}
A global 404 page
For URLs that do not match any route at all (such as /random-page), create app/not-found.tsx:
// app/not-found.tsx
import Link from 'next/link'
export default function NotFound() {
return (
<div className="py-12 text-center">
<h1 className="text-3xl font-bold">404: Halaman tidak ditemukan</h1>
<p className="mt-2 text-gray-600">Alamat yang Anda buka tidak tersedia.</p>
<Link href="/" className="mt-6 inline-block text-blue-600 hover:underline">
Kembali ke beranda
</Link>
</div>
)
}
Try opening /products/template-dashboard-admin (the unpublished product) and /products/does-not-exist. Result: both show "Produk tidak ditemukan" together with the catalog sidebar. Then open /random-page. Result: the root "404: Halaman tidak ditemukan" page.
Be careful with
try/catch: becausenotFound()works by throwing, wrapping it in atry/catch"swallows" the signal and the 404 page never appears.
loading.tsx: The Loading Screen
Building a skeleton
We gave getProductBySlug an 800 ms delay to imitate a database query. Without an indicator, users may think the app has frozen. Create app/products/[slug]/loading.tsx:
// app/products/[slug]/loading.tsx
export default function Loading() {
return (
<div role="status" aria-live="polite" className="animate-pulse space-y-3">
<div className="h-4 w-24 rounded bg-gray-200" />
<div className="h-8 w-2/3 rounded bg-gray-200" />
<div className="h-6 w-32 rounded bg-gray-200" />
<div className="h-4 w-full rounded bg-gray-200" />
<span className="sr-only">Memuat produk...</span>
</div>
)
}
Click any product. Result: pulsing grey boxes appear briefly in the content area while the header and sidebar stay in place, then the product details replace them. The sr-only text and role="status" make screen readers announce that content is loading.
How it works
loading.tsx automatically wraps the page.tsx in the same folder (and its children) in a React <Suspense> boundary. While the page is still waiting for data, the loading.tsx content is shown. The layout in the same folder is not wrapped, so the sidebar keeps showing.
There is an extra reason loading.tsx matters in our project. Because Cache Components is enabled (the default from Part 1), Next.js builds a "static shell" of each page at build time. The value of params is only known when a request arrives, so reading params must happen inside a <Suspense> boundary. loading.tsx provides that boundary for the whole page. Without a Suspense boundary, Next.js shows an error asking you to add one. The alternative, preparing the list of slugs at build time with generateStaticParams, is covered in Part 7.
One small note: because the loading UI has already been sent, the response for a missing product still has HTTP status 200, but Next.js automatically adds a noindex meta tag so search engines do not index it. We dig into status codes and SEO in Part 11.
Current Folder Structure
digistore/
βββ app/
β βββ layout.tsx β root layout + header
β βββ page.tsx β /
β βββ not-found.tsx β global 404
β βββ products/
β βββ layout.tsx β catalog sidebar
β βββ page.tsx β /products
β βββ [slug]/
β βββ page.tsx β /products/:slug
β βββ loading.tsx
β βββ not-found.tsx
βββ lib/
βββ products.ts β temporary data
Common Mistakes
- Not awaiting params. Writing
params.slugwithoutawaitgivesundefinedor a type error. Always useconst { slug } = await params. - Wrong folder name. A dynamic segment is a folder named
[slug]containingpage.tsx, not a file named[slug].tsx. - Using
<a>for internal links. The page fully reloads and the layout is loaded again. Use<Link>. - Forgetting to render
childrenin a layout. The page will not appear at all. - Putting
<html>or<body>in a nested layout. Those tags belong only in the root layout. - Wrapping
notFound()intry/catch. The 404 signal is swallowed and the page does not render as intended. - Showing unpublished products. The
publishedfilter must live in the data-access function, not just be hidden in the UI.
Exercises
- Create an
/aboutpage (app/about/page.tsx) describing DigiStore, then add a "Tentang" (About) link to the header. - Add a seventh product to the array in
lib/products.tsand confirm it automatically appears in the list, in the sidebar and on its own detail page, without changing any page file. - Create
app/products/loading.tsxwith a skeleton for the product list. Then add a temporary delay togetProductsand observe where the skeleton appears. Revert the delay afterwards.
Summary
- Folders in
app/become URL segments; a route is accessible when it has apage.tsx. layout.tsxwraps pages and does not re-render on navigation. Layouts can be nested (root layout β products layout β page).<Link>gives you client-side navigation and prefetching.- The dynamic segment
[slug]passes part of the URL intoparams, which in Next.js 16 is a Promise:const { slug } = await params. notFound()renders the nearestnot-found.tsx;app/not-found.tsxhandles unknown URLs.loading.tsxshows temporary UI through Suspense and, with Cache Components, also acts as the Suspense boundary for readingparams.
Every page we have built so far is a Server Component. In Part 3 we meet Client Components, build interactive favorite and "Tambah ke Keranjang" (Add to Cart) buttons, and move the header into its own component. See you there!
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 #1: Introduction & Setup
Start your PHP journey: what PHP is, how to install PHP 8.2+, run the built-in development server, and write your very first script with echo.
Ruby on Rails Zero to Advanced #1: Ruby Basics
Start the Rails journey with the language underneath it: irb, variables, strings, puts vs p, and symbols explained with runnable examples.