Next.js Zero to Advanced #4: Styling with Tailwind CSS, next/image & next/font
Welcome back to the Next.js Zero to Advanced series! In Part 3 we learned the difference between Server Components and Client Components and added a bit of interactivity to DigiStore. But it still looks plain. In this Part 4 we will make DigiStore look like a real store: a responsive product grid with Tailwind CSS, a reusable button component, optimized images with next/image, clean typography with next/font, prices in Rupiah format, and metadata so the browser tab titles are more informative.
By the end of this part, the /products page will show product cards with an image, category and price, laid out in 1 column on phones, 2 on tablets and 3 on desktops.
Tailwind CSS v4 from create-next-app
When we created the project in Part 1, we chose Tailwind CSS in create-next-app. Next.js 16 installs Tailwind CSS v4, which is much simpler to configure than version 3: there is no tailwind.config.js file anymore. Everything is configured from CSS.
Looking at globals.css
Open app/globals.css. The most important part looks roughly like this:
@import "tailwindcss";
:root {
--background: #ffffff;
--foreground: #171717;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}
The line @import "tailwindcss"; loads all of Tailwind's utility classes. The @theme block defines design tokens such as colors and fonts. Every --color-* variable inside @theme automatically becomes classes like bg-* and text-*. This file is already imported in app/layout.tsx (import './globals.css'), so it applies to every page.
Note: if you find other tutorials that use
tailwind.config.jsand@tailwind base;, that is the Tailwind v3 way. In our project created with create-next-app 16,@import "tailwindcss";is all you need.
Adding DigiStore brand colors
To keep colors consistent across the app, we define one brand palette. Replace the contents of app/globals.css with:
@import "tailwindcss";
:root {
--background: #ffffff;
--foreground: #171717;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-jakarta);
--font-mono: var(--font-geist-mono);
}
/* DigiStore brand colors -> bg-brand-600, text-brand-700, ring-brand-500, ... */
@theme {
--color-brand-50: #eef6ff;
--color-brand-500: #3b82f6;
--color-brand-600: #2563eb;
--color-brand-700: #1d4ed8;
}
body {
background: var(--background);
color: var(--foreground);
}
Now we have classes like bg-brand-600, text-brand-700 and ring-brand-500. If the brand color ever changes, you only change it in this one place. Also note --font-sans: var(--font-jakarta); we will create the --font-jakarta variable with next/font shortly.
Reading utility classes
Tailwind works by writing small classes directly in JSX. For example:
<p className="mt-2 text-sm text-gray-600 md:text-base">
Template dan source code siap pakai.
</p>
mt-2: margin-top 0.5rem.text-sm: a small font size;md:text-base: from medium screen width (768px) up, the size becomes normal.text-gray-600: a gray color from Tailwind's built-in palette.
Prefixes such as sm:, md: and lg: are the key to responsive design. Tailwind is mobile-first: classes without a prefix apply to all screen sizes, and prefixed classes override them from a certain width upward.
The formatRupiah helper
Prices in our data are stored as whole numbers in Rupiah (for example 149000), matching the price Int column we will create in the database in Part 6. To display them, create lib/format.ts:
// lib/format.ts
const rupiahFormatter = new Intl.NumberFormat('id-ID', {
style: 'currency',
currency: 'IDR',
maximumFractionDigits: 0,
})
export function formatRupiah(amount: number): string {
return rupiahFormatter.format(amount)
}
Result:
formatRupiah(149000) // "Rp 149.000"
formatRupiah(0) // "Rp 0"
We create the Intl.NumberFormat once outside the function so it is not rebuilt on every call. The maximumFractionDigits: 0 option removes the trailing ",00" because Rupiah has no cents. A small note: the space between "Rp" and the number may be a special (non-breaking) space character, so do not compare the output string by hand in tests.
A reusable Button component
Instead of repeating long button class lists, we create one component in components/ui/Button.tsx. Every button in DigiStore later on (Buy, Save in the admin, Logout) will use it.
// components/ui/Button.tsx
import type { ButtonHTMLAttributes } from 'react'
type Variant = 'primary' | 'secondary' | 'ghost'
type Size = 'sm' | 'md'
const base =
'inline-flex items-center justify-center gap-2 rounded-lg font-semibold transition-colors ' +
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-500 focus-visible:ring-offset-2 ' +
'disabled:cursor-not-allowed disabled:opacity-50'
const variants: Record<Variant, string> = {
primary: 'bg-brand-600 text-white hover:bg-brand-700',
secondary: 'border border-gray-300 bg-white text-gray-900 hover:bg-gray-50',
ghost: 'text-gray-700 hover:bg-gray-100',
}
const sizes: Record<Size, string> = {
sm: 'h-9 px-3 text-sm',
md: 'h-11 px-5 text-base',
}
// Reusable for <Link> too, so links and buttons look the same.
export function buttonClasses(variant: Variant = 'primary', size: Size = 'md', extra = '') {
return [base, variants[variant], sizes[size], extra].join(' ')
}
type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
variant?: Variant
size?: Size
}
export function Button({
variant = 'primary',
size = 'md',
className = '',
type = 'button',
...props
}: ButtonProps) {
return <button type={type} className={buttonClasses(variant, size, className)} {...props} />
}
Explanation
- Variant and size: the button has three styles (
primary,secondary,ghost) and two sizes. This keeps the UI consistent. buttonClasses(): a function that returns the class string. Useful for a<Link>that should look like a button, without wrapping a link inside a button (which is invalid HTML).type = 'button'by default: a button inside a form will not accidentally submit it. For submit buttons, writetype="submit"explicitly.focus-visible:ring-2: shows a clear outline when the button is focused with the keyboard. This matters for accessibility.- This component does not use
"use client"because it has no state or hooks. It can still be used inside a Client Component (such as the interactive button from Part 3) and receive anonClickfrom there.
A responsive Header
Update components/Header.tsx to use the brand color and buttonClasses:
// components/Header.tsx
import Link from 'next/link'
import { buttonClasses } from '@/components/ui/Button'
export function Header() {
return (
<header className="sticky top-0 z-10 border-b border-gray-200 bg-white/90 backdrop-blur">
<nav className="mx-auto flex h-16 max-w-6xl items-center justify-between px-4">
<Link href="/" className="text-lg font-bold text-brand-700">
DigiStore
</Link>
<div className="flex items-center gap-2">
<Link href="/products" className={buttonClasses('ghost', 'sm')}>
Produk
</Link>
<Link href="/products" className={buttonClasses('primary', 'sm', 'hidden sm:inline-flex')}>
Mulai Belanja
</Link>
</div>
</nav>
</header>
)
}
The classes hidden sm:inline-flex hide the "Mulai Belanja" (Start Shopping) button on small screens and show it from 640px up. The header is also sticky, so it stays visible while scrolling.
ProductCard and a responsive grid
Checking the product data shape
In Part 2 we created product data in lib/products.ts. Make sure the Product type has the following fields. The imageUrl field may be null for products without an image yet. We deliberately match the shape of the database Product model we will build later, so moving to Prisma in Part 7 goes smoothly.
// lib/products.ts (excerpt)
export type Category = 'EBOOK' | 'SOURCE_CODE' | 'TEMPLATE'
export type Product = {
id: string
slug: string
title: string
description: string
price: number // rupiah, no decimals
category: Category
imageUrl: string | null
published: boolean
}
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,
},
// ...p2 to p4 from Part 2
{
id: 'p5',
slug: 'template-landing-page',
title: 'Template Landing Page',
description: 'Landing page responsif berbasis Tailwind CSS.',
price: 149000,
category: 'TEMPLATE',
imageUrl: null, // no image yet -> the card shows a fallback
published: true,
},
// ...p6 from Part 2
]
// getProducts() and getProductBySlug() from Part 2 stay the same
Put a few images (JPG or PNG, for example with a 4:3 ratio) in the public/products/ folder. Files in public are served from the base URL, so public/products/ebook-belajar-nextjs.jpg becomes /products/ebook-belajar-nextjs.jpg.
digistore/
βββ public/
β βββ products/
β βββ ebook-belajar-nextjs.jpg
β βββ ...
βββ components/
β βββ ui/Button.tsx
β βββ Header.tsx
β βββ ProductCard.tsx
βββ lib/
βββ format.ts
βββ products.ts
Creating ProductCard
// components/ProductCard.tsx
import Image from 'next/image'
import Link from 'next/link'
import { formatRupiah } from '@/lib/format'
import type { Product } from '@/lib/products'
const categoryLabel: Record<Product['category'], string> = {
EBOOK: 'E-book',
SOURCE_CODE: 'Source Code',
TEMPLATE: 'Template',
}
export function ProductCard({ product }: { product: Product }) {
return (
<Link
href={`/products/${product.slug}`}
className="group flex flex-col overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm transition hover:-translate-y-0.5 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-500"
>
<div className="relative aspect-[4/3] bg-gray-100">
{product.imageUrl ? (
<Image
src={product.imageUrl}
alt={product.title}
fill
sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw"
className="object-cover"
/>
) : (
<div className="flex h-full items-center justify-center text-sm text-gray-500">
Belum ada gambar
</div>
)}
</div>
<div className="flex flex-1 flex-col gap-2 p-4">
<span className="w-fit rounded-full bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-700">
{categoryLabel[product.category]}
</span>
<h3 className="font-semibold text-gray-900 group-hover:text-brand-700">
{product.title}
</h3>
<p className="line-clamp-2 text-sm text-gray-600">{product.description}</p>
<p className="mt-auto pt-2 text-lg font-bold text-gray-900">
{formatRupiah(product.price)}
</p>
</div>
</Link>
)
}
A few important points about this component:
- The whole card is a
Link, so the click area is large and comfortable on phones. - The image uses
fillinside arelative aspect-[4/3]container. That way every card has the same image height and there is no layout shift. - The
sizesprop tells the browser the image is 100% of the screen width on phones, 50% on tablets and 33% on desktops. Next.js then generates the rightsrcset, so phones don't download desktop-sized images. - If
imageUrlis empty, we show a "Belum ada gambar" (No image yet) fallback instead of a broken image. - This is a Server Component: no extra JavaScript is sent to the browser to render the card.
Laying out the grid on the products page
Now use ProductCard in app/products/page.tsx:
// app/products/page.tsx
import type { Metadata } from 'next'
import { ProductCard } from '@/components/ProductCard'
import { getProducts } from '@/lib/products'
export const metadata: Metadata = {
title: 'Semua Produk',
description: 'E-book, source code, dan template digital siap pakai.',
}
export default async function ProductsPage() {
const products = await getProducts() // published products only
return (
<main className="mx-auto max-w-6xl px-4 py-10">
<h1 className="text-2xl font-bold text-gray-900 md:text-3xl">Semua Produk</h1>
<p className="mt-1 text-gray-600">{products.length} produk tersedia</p>
{products.length === 0 ? (
<p className="mt-10 rounded-xl border border-dashed border-gray-300 p-10 text-center text-gray-500">
Belum ada produk. Silakan kembali lagi nanti.
</p>
) : (
<ul className="mt-8 grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
{products.map((product) => (
<li key={product.id}>
<ProductCard product={product} />
</li>
))}
</ul>
)}
</main>
)
}
The responsive key is grid-cols-1 sm:grid-cols-2 lg:grid-cols-3: one column by default, two from 640px and three from 1024px. We also handle the empty state: if the product array is empty, users see a clear message instead of a blank page. In Part 7 this data will come from the database and we will add search, filters and pagination.
Run npm run dev, open http://localhost:3000/products, then resize the browser window (or use device mode in DevTools) to watch the grid change.
Optimizing images with next/image
The <Image> component from next/image is a replacement for <img> that automatically resizes images per device, serves modern formats such as WebP, defers loading of off-screen images (lazy loading) and prevents layout shift.
Local vs remote images
For images in the public folder, you just write a path such as /products/name.jpg. Because we use fill, we don't need width and height. Without fill, width and height are required so Next.js knows the image's aspect ratio.
For images from another server (for example a storage bucket or CDN where sellers upload product covers), Next.js rejects URLs that are not allowed yet. This is a security feature: without an allowlist, anyone could use your server to optimize images from anywhere. Register the allowed hosts in next.config.ts with remotePatterns:
// next.config.ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true, // from Part 1: keep these
partialPrefetching: true,
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'cdn.example.com',
port: '',
pathname: '/digistore/**',
search: '',
},
],
},
}
export default nextConfig
The configuration above only allows URLs starting with https://cdn.example.com/digistore/ without a query string. Replace cdn.example.com with your own storage host once you have one. Other URLs get a 400 Bad Request response. Make patterns as specific as possible and avoid wildcards like hostname: '**'. Restart npm run dev after changing next.config.ts.
What changed in Next.js 16
- The
priorityprop is deprecated and replaced bypreload. Usepreloadonly for the main above-the-fold image (usually the Largest Contentful Paint element), such as the large image on the detail page. Alternatives areloading="eager"orfetchPriority="high". - The
images.qualitiessetting now defaults to[75]. If you writequality={90}without adding 90 to thequalitieslist, it is coerced to the closest allowed value. - By default, Next.js does not optimize images from local/private IP addresses (
dangerouslyAllowLocalIPisfalse). Keep it that way unless you understand the risk.
The main image on the detail page
On the app/products/[slug]/page.tsx page from Part 2, the product image is the largest element above the fold, so it is a good candidate for preload:
// app/products/[slug]/page.tsx (image part only)
<div className="relative aspect-[4/3] overflow-hidden rounded-xl bg-gray-100">
{product.imageUrl ? (
<Image
src={product.imageUrl}
alt={product.title}
fill
preload
sizes="(max-width: 768px) 100vw, 50vw"
className="object-cover"
/>
) : (
<div className="flex h-full items-center justify-center text-gray-500">Belum ada gambar</div>
)}
</div>
Don't forget import Image from 'next/image' in that file. On the list page, don't use preload on every card; preloading too many images actually slows the page down.
Clean typography with next/font
next/font downloads fonts at build time and serves them from your own domain (self-hosting). The result: no requests to Google from your visitors' browsers, faster loading and no layout shift while the font loads. We will use Plus Jakarta Sans, an open-source font made in Indonesia, as DigiStore's main font.
// app/layout.tsx
import type { Metadata } from 'next'
import { Geist_Mono, Plus_Jakarta_Sans } from 'next/font/google'
import { Header } from '@/components/Header'
import './globals.css'
const jakarta = Plus_Jakarta_Sans({
subsets: ['latin'],
display: 'swap',
variable: '--font-jakarta',
})
const geistMono = Geist_Mono({
subsets: ['latin'],
variable: '--font-geist-mono',
})
export const metadata: Metadata = {
title: {
default: 'DigiStore β Produk Digital Siap Pakai',
template: '%s | DigiStore',
},
description: 'Marketplace mini untuk e-book, source code, dan template.',
}
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="id" className={`${jakarta.variable} ${geistMono.variable}`}>
<body className="min-h-screen bg-gray-50 font-sans text-gray-900 antialiased">
<Header />
{children}
</body>
</html>
)
}
Explanation
- Font names in
next/font/googleuse underscores: "Plus Jakarta Sans" becomesPlus_Jakarta_Sans. Because it is a variable font, we don't need to specify aweight. - The
variable: '--font-jakarta'option creates a CSS variable. It is attached to<html>viajakarta.variable, then connected to Tailwind through--font-sans: var(--font-jakarta)inglobals.css. As a result, thefont-sansclass uses Plus Jakarta Sans. - The font is loaded in the root layout so it applies to the whole app. Call the font function at module level (outside the component), not inside the component function.
- We also changed
lang="en"tolang="id"because DigiStore's content is in Indonesian. This helps screen readers and search engines.
Static metadata
In the layout above we already exported a metadata object. Next.js reads it and generates the <title> and <meta name="description"> tags automatically. The metadata object can only be exported from a Server Component (layout.tsx or page.tsx), not from a file with "use client".
With title.template, child pages only need a short title. The /products page exports title: 'Semua Produk', so the result is:
/ -> <title>DigiStore β Produk Digital Siap Pakai</title>
/products -> <title>Semua Produk | DigiStore</title>
For the product detail page, the title depends on data (the product name). That requires generateMetadata, which we will cover in Part 11 together with Open Graph and the sitemap.
Common mistakes
- Writing a Tailwind v3-style
tailwind.config.js. In this project Tailwind v4 is configured from CSS via@theme. The old config file is not read. - Building class names dynamically with template strings, such as
`bg-${color}-600`. Tailwind scans source code for complete class names, so classes assembled like this are not generated. Write full class names, as in thevariantsobject of Button. - Forgetting
relativeon the parent of afillimage. Afillimage usesposition: absolute, so its container must berelativeand have a height (here viaaspect-[4/3]). - The "hostname is not configured under images" error. The remote image host is not registered in
remotePatterns, or the dev server was not restarted. - Using
priority. In Next.js 16 usepreload, and only for one main image. - Empty or careless
alttext.altis required innext/image; fill it with a meaningful description such as the product title.
Exercises
- Add a
danger(red) variant toButton. It will be useful for the delete-product button in Part 8. - Change the grid to show 4 columns on very wide screens (
xl:), and adjust thesizesprop inProductCardaccordingly. - Add
export const metadatatoapp/page.tsxwith a description specific to the home page, then inspect the<title>and<meta>tags in DevTools.
Summary
- Tailwind CSS v4 is enabled with
@import "tailwindcss";, and design tokens (colors, fonts) are defined in@theme. - The
sm:,md:andlg:prefixes make layouts responsive with a mobile-first approach. components/ui/Button.tsxandbuttonClasses()keep buttons and links consistent.next/imageoptimizes images; usefill+sizesfor cards,remotePatternsfor remote hosts, andpreload(notpriority) for the main image.next/fontserves fonts from your own domain and connects to Tailwind via a CSS variable.formatRupiah()inlib/format.tsdisplays prices in Indonesian format.- A
metadataobject withtitle.templateproduces consistent tab titles.
DigiStore's look is ready, but its data is still an in-memory array that resets every time we change the code. In Part 5 we will set up a PostgreSQL database as a permanent home for products, users and orders. 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.