Next.js Zero to Advanced #11: Error Handling, SEO & Production Readiness
In Part 10 we secured DigiStore with login, a session cookie and requireAdmin(). The features are complete, but an app that "works on my laptop" is not necessarily production-ready. In Part 11 we tidy up error handling (error.tsx, global-error.tsx, not-found.tsx), add SEO with generateMetadata and Open Graph, create sitemap.ts and robots.ts, read the npm run build output, run the linter, build an environment variable checklist, and add basic security headers in next.config.ts.
Layered Error Handling
Next.js provides several special files for handling errors. Each one catches a different kind of problem:
| File | When it is used |
|---|---|
not-found.tsx | The URL matches no route, or code calls notFound(). |
error.tsx | A render error in that segment and its children (for example the database is down). |
global-error.tsx | An error in the root layout itself. This is the last safety net. |
Root error.tsx
In Part 7 we created an error.tsx for the product pages. Now add one at app/error.tsx so every page is covered. Error boundaries must be Client Components.
// app/error.tsx
'use client'
import { useEffect } from 'react'
export default function ErrorPage({
error,
retry,
}: {
error: Error & { digest?: string }
retry: () => void
}) {
useEffect(() => {
console.error(error) // swap for an error reporting service if you have one
}, [error])
return (
<main className="mx-auto max-w-md px-4 py-16 text-center">
<h1 className="text-2xl font-bold">Something went wrong</h1>
<p className="mt-2 text-gray-600">Sorry, this page failed to load. Please try again.</p>
{error.digest && (
<p className="mt-2 text-xs text-gray-400">Error code: {error.digest}</p>
)}
<button
onClick={() => retry()}
className="mt-6 rounded-md bg-blue-600 px-4 py-2 font-medium text-white"
>
Try again
</button>
</main>
)
}Two important details from the Next.js 16 docs:
- The
retry()prop has been stable since Next.js 16.3. It re-fetches data and re-renders the segment. Thereset()prop you may see in older tutorials still exists, but it only re-renders without re-fetching. Theapp/products/error.tsxfrom Part 7 already usesretry, so both error boundaries behave the same;retryis the better fit for transient errors such as a dropped database connection. - In production, error messages from Server Components are not sent to the browser, so sensitive details (queries, file paths) do not leak. All that remains is
error.digest, a code you can match against server logs. We will use it when reading logs in Part 12.
global-error.tsx
If the root layout itself fails (for example UserMenu in the Header cannot reach the database), app/error.tsx cannot help because it lives inside that layout. For this case we need app/global-error.tsx. This file replaces the whole document, so it must have its own <html> and <body> tags and must import global CSS explicitly. metadata exports are not supported here, so we use React's <title> element.
// app/global-error.tsx
'use client'
import './globals.css'
export default function GlobalError({
error,
retry,
}: {
error: Error & { digest?: string }
retry: () => void
}) {
return (
<html lang="id">
<body>
<title>Something went wrong | DigiStore</title>
<main className="mx-auto max-w-md px-4 py-16 text-center">
<h1 className="text-2xl font-bold">DigiStore is having trouble</h1>
{error.digest && <p className="mt-2 text-xs text-gray-400">{error.digest}</p>}
<button onClick={() => retry()} className="mt-6 rounded-md border px-4 py-2">
Try again
</button>
</main>
</body>
</html>
)
}not-found.tsx
We have been calling notFound() since Part 2. Make sure the global 404 page is friendly and points users back to the catalog. This component receives no props.
// app/not-found.tsx
import Link from 'next/link'
export default function NotFound() {
return (
<main className="mx-auto max-w-md px-4 py-16 text-center">
<h1 className="text-2xl font-bold">404: Page not found</h1>
<p className="mt-2 text-gray-600">The product or page you are looking for does not exist.</p>
<Link href="/products" className="mt-6 inline-block text-blue-600 underline">
Back to the catalog
</Link>
</main>
)
}SEO: Base Metadata in the Root Layout
In Part 4 we used a simple static metadata. For production, add metadataBase so relative URLs (canonical, Open Graph images) become absolute automatically, and title.template so every page gets a " | DigiStore" suffix. Keep the site URL in an environment variable so it can differ between local and production:
// lib/site.ts
export const siteUrl = process.env.SITE_URL ?? 'http://localhost:3000'
export const siteName = 'DigiStore'// app/layout.tsx (metadata section only)
import type { Metadata } from 'next'
import { siteName, siteUrl } from '@/lib/site'
export const metadata: Metadata = {
metadataBase: new URL(siteUrl),
title: {
default: 'DigiStore - Digital Product Store',
template: `%s | ${siteName}`,
},
description: 'E-books, source code and ready-made templates for developers.',
openGraph: { siteName, locale: 'id_ID', type: 'website' },
}generateMetadata for Each Product
The title and description of the detail page must come from the database. Both generateMetadata and the page need the same data, so we reuse getProductBySlug from Part 7. It is already cached with 'use cache' and the products tag, so the database is not queried twice, it only returns published products, and the updateTag('products') from Part 8 refreshes the metadata too. Remember, in Next.js 16 params is a Promise.
// app/products/[slug]/page.tsx
import type { Metadata } from 'next'
import { notFound } from 'next/navigation'
import { getProductBySlug } from '@/lib/products'
import { siteName } from '@/lib/site'
type Props = { params: Promise<{ slug: string }> }
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params
const product = await getProductBySlug(slug)
if (!product) {
return { title: 'Product not found', robots: { index: false } }
}
const description = product.description.slice(0, 155)
const url = `/products/${product.slug}`
return {
title: product.title,
description,
alternates: { canonical: url },
openGraph: {
siteName, // the layout openGraph is replaced, not merged
type: 'website',
title: product.title,
description,
url,
images: product.imageUrl ? [{ url: product.imageUrl, alt: product.title }] : undefined,
},
}
}
export default async function ProductPage({ params }: Props) {
const { slug } = await params
const product = await getProductBySlug(slug)
if (!product) notFound()
// ...product detail JSX and the Buy form from Part 10
}Metadata from multiple segments is merged shallowly: the page's openGraph object replaces the layout's whole openGraph. That is why we repeat siteName. Open a product, right-click and choose View Page Source. Result:
<title>E-book Belajar Next.js | DigiStore</title>
<meta name="description" content="Panduan praktis membangun aplikasi web dengan Next.js."/>
<link rel="canonical" href="http://localhost:3000/products/ebook-belajar-nextjs"/>
<meta property="og:title" content="E-book Belajar Next.js"/>
<meta property="og:url" content="http://localhost:3000/products/ebook-belajar-nextjs"/>
<meta property="og:site_name" content="DigiStore"/>If there is no imageUrl, you can add an app/opengraph-image.png file as the site-wide default image, or generate images dynamically with ImageResponse from next/og.
sitemap.ts and robots.ts
A sitemap helps search engines discover every product. We generate it from the database and only include published products:
// app/sitemap.ts
import type { MetadataRoute } from 'next'
import { cacheLife, cacheTag } from 'next/cache'
import { prisma } from '@/lib/prisma'
import { siteUrl } from '@/lib/site'
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
return getSitemapEntries()
}
async function getSitemapEntries(): Promise<MetadataRoute.Sitemap> {
'use cache'
cacheLife('hours') // refreshed in the background about once per hour
cacheTag('products') // updateTag('products') from Part 8 refreshes it immediately
const products = await prisma.product.findMany({
where: { published: true },
select: { slug: true, updatedAt: true },
})
return [
{ url: siteUrl, lastModified: new Date(), changeFrequency: 'daily', priority: 1 },
{ url: `${siteUrl}/products`, lastModified: new Date(), changeFrequency: 'daily', priority: 0.8 },
...products.map((product) => ({
url: `${siteUrl}/products/${product.slug}`,
lastModified: product.updatedAt,
changeFrequency: 'weekly' as const,
priority: 0.6,
})),
]
}// app/robots.ts
import type { MetadataRoute } from 'next'
import { siteUrl } from '@/lib/site'
export default function robots(): MetadataRoute.Robots {
return {
rules: {
userAgent: '*',
allow: '/',
disallow: ['/admin', '/orders', '/api/', '/login', '/register'],
},
sitemap: `${siteUrl}/sitemap.xml`,
}
}Open http://localhost:3000/robots.txt. Result:
User-Agent: *
Allow: /
Disallow: /admin
Disallow: /orders
Disallow: /api/
Disallow: /login
Disallow: /register
Sitemap: http://localhost:3000/sitemap.xml
robots.txtis only a polite request to crawlers, not a security control. The file itself is public, so never list secret paths in it. Protection for/adminstill comes fromrequireAdmin()in Part 10.
The Next.js docs explain that sitemap.ts is a special Route Handler that is cached by default, so it is generated during next build. That means the database must be reachable at build time. Keep this in mind when deploying in Part 12.
Older tutorials refresh a sitemap with export const revalidate = 3600. With Cache Components (on since Part 1), route segment config such as revalidate and dynamic is no longer allowed and makes the build fail. Its replacement is the code above: the query lives in a function marked 'use cache', cacheLife('hours') sets how long the result may be reused (revalidated in the background about once an hour, the same profile as the catalog in Part 7), and cacheTag('products') makes the sitemap refresh immediately whenever an admin changes a product. new Date() sits inside the cached function on purpose: with Cache Components, a timestamp outside a cache scope has to be explicitly deferred to request time.
Linting and the Production Build
npm run lint
In Next.js 16, the next lint command was removed and next build no longer runs linting. The lint script from create-next-app calls ESLint directly, so run it separately:
npm run lintFix every error before moving on. Warnings such as unused variables are best cleaned up too so they do not pile up.
npm run build
Make sure your local PostgreSQL is running (the sitemap needs the database), then:
npm run build
npm run startThe build also runs TypeScript checks. At the end, Next.js prints a route table. Result (shortened, your output may differ slightly):
Route (app)
β β /
β β /admin/products
β Ζ /api/products
β Ζ /api/products/[id]
β β /login
β β /orders
β β /products
β β /products/[slug]
β β /register
β β /robots.txt
β β /sitemap.xml
Ζ Proxy (Middleware)
β (Static) prerendered as static content
β (Partial Prerender) prerendered as static HTML with dynamic server-streamed content
Ζ (Dynamic) server-rendered on demandWhat the symbols mean: β Static means the whole response is generated at build time. β Partial Prerender is what Cache Components produces: a static shell (layout, headings, Suspense fallbacks and 'use cache' data such as the catalog from Part 7) is prerendered at build time and served instantly, while the parts that need the request stream in afterwards. Ζ Dynamic means everything is rendered per request; here that is only the API Route Handlers, which read the incoming request. Why are almost all pages β rather than β? Because the root layout's Header renders UserMenu inside <Suspense> (Part 10), so every page has at least one small hole that depends on the session cookie, and pages such as /products and /orders also read searchParams or the session inside their own Suspense boundaries. Reading cookies there does not make the whole route dynamic: the rest of the page is still served from the static shell. If you use generateStaticParams (Part 7), the listed product URLs get their own prerendered shells.
Basic Security Headers
The following HTTP headers add an extra layer of protection in the browser. Merge them with the images.remotePatterns config from Part 4 in next.config.ts:
// next.config.ts
import type { NextConfig } from 'next'
const securityHeaders = [
{ key: 'X-Content-Type-Options', value: 'nosniff' },
{ key: 'X-Frame-Options', value: 'DENY' },
{ key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
{ key: 'Permissions-Policy', value: 'camera=(), microphone=(), geolocation=(), browsing-topics=()' },
{ key: 'Strict-Transport-Security', value: 'max-age=63072000; includeSubDomains' },
]
const nextConfig: NextConfig = {
cacheComponents: true, // from Part 1: keep these
partialPrefetching: true,
poweredByHeader: false, // hide the X-Powered-By header
// images: { remotePatterns: [...] }, keep your config from Part 4
async headers() {
return [{ source: '/:path*', headers: securityHeaders }]
},
}
export default nextConfig- X-Content-Type-Options: nosniff stops the browser from guessing file types.
- X-Frame-Options: DENY stops DigiStore from being loaded inside another site's iframe (clickjacking).
- Referrer-Policy limits how much of the URL is sent to other sites.
- Permissions-Policy disables camera, microphone and location access that we do not use.
- Strict-Transport-Security forces HTTPS. Browsers ignore it on
http://localhost, so it is safe in development.
Check with curl while npm run start is running:
curl -I http://localhost:3000/productsResult (partial):
HTTP/1.1 200 OK
x-content-type-options: nosniff
x-frame-options: DENY
referrer-policy: strict-origin-when-cross-origin
permissions-policy: camera=(), microphone=(), geolocation=(), browsing-topics=()
strict-transport-security: max-age=63072000; includeSubDomainsA stronger next step is a Content Security Policy (CSP). A strict CSP usually needs a nonce generated in proxy.ts, so read the "Content Security Policy" guide in the Next.js docs before adding it.
Environment Variable Checklist
| Variable | Used in | Secret? |
|---|---|---|
DATABASE_URL | Prisma (runtime, migrations, sitemap build) | Yes |
SESSION_SECRET | lib/session.ts, at least 32 characters | Yes |
SITE_URL | metadataBase, sitemap, robots | No |
SEED_ADMIN_PASSWORD, SEED_USER_PASSWORD | Only prisma/seed.ts, not needed on the production server | Yes |
Create an .env.example file that may be committed, listing variable names without secret values, so teammates (and you in Part 12) know what has to be filled in:
# .env.example
DATABASE_URL="postgresql://db_user:YOUR_PASSWORD@localhost:5432/digistore"
SESSION_SECRET=""
SITE_URL="http://localhost:3000"
SEED_ADMIN_PASSWORD=""
SEED_USER_PASSWORD=""Make sure .gitignore ignores .env but not .env.example. Also remember: never give a secret variable the NEXT_PUBLIC_ prefix, because its value is bundled into the browser at build time.
Common Mistakes
- Writing
global-error.tsxwithout<html>and<body>, or forgetting that it does not load global CSS automatically. - Showing the raw
error.messagefrom the server to users. Show a generic message and thedigestonly. - Forgetting
metadataBase, so relative URLs in metadata cause a build error. - Including unpublished products in the sitemap, which leaks unreleased products.
- Treating
robots.txtas a security control. - Assuming
npm run buildruns lint. In Next.js 16 it no longer does. Runnpm run lintyourself.
Exercises
- Create a product-specific
app/products/[slug]/not-found.tsxthat shows "Product not found" and links to the three newest products. - Create
app/products/[slug]/opengraph-image.tsxwithImageResponsefromnext/ogthat renders the product title and price in rupiah. - Add
ProductJSON-LD structured data to the detail page (see the JSON-LD guide in the Next.js docs), then check the output in View Page Source.
Summary
not-found.tsx,error.tsx(withretry()) andglobal-error.tsxform layers of error handling. In production, server error details are hidden and replaced by adigest.metadataBase,title.templateandgenerateMetadatawith the cachedgetProductBySluggive every product its own title, description, canonical URL and Open Graph tags.sitemap.tsis generated from the database (published products only) and cached with'use cache'+cacheLifeinstead ofexport const revalidate, whilerobots.tsguides crawlers but is not a security control.- The build output shows β static, β partially prerendered and Ζ dynamic routes. Linting runs separately in Next.js 16.
- Security headers and the environment variable checklist are ready for production.
DigiStore is now ready to ship. In Part 12, the final part of this series, we will deploy it to Vercel with a managed PostgreSQL database, run migrations in production, attach a custom domain and read the logs.
Related articles
PostgreSQL Zero to Advanced #8: Indexes & Performance
Read query plans with EXPLAIN ANALYZE and speed up a 500,000-row table with B-tree, composite, partial and GIN indexes.
PHP Zero to Advanced #8: Composer, Namespaces, PSR-4 Autoloading & Exceptions
Structure real PHP projects: organize code with namespaces, manage dependencies with Composer, autoload classes with PSR-4, and handle errors cleanly with exceptions.
Ruby on Rails Zero to Advanced #8: Forms, Strong Parameters & Full CRUD
Build a complete CRUD feature by hand with form_with and strong parameters, then compare it with what rails generate scaffold gives you for free.