Metadata, SEO, errors and Proxy
A production app needs good SEO and social previews, friendly error and 404 pages, and sometimes logic that runs before a request reaches a page. Next.js has a convention for each.
Static metadata
Export a metadata object from a layout.tsx or page.tsx (Server Components only):
// app/layout.tsx
import type { Metadata } from 'next';
export const metadata: Metadata = {
title: {
default: 'Learn to Code',
template: '%s | Learn to Code', // child pages fill in %s
},
description: 'Free lessons from scratch to pro.',
metadataBase: new URL('https://learntocode.example'),
openGraph: { type: 'website', siteName: 'Learn to Code' },
};// app/pricing/page.tsx
export const metadata = { title: 'Pricing' }; // → <title>Pricing | Learn to Code</title>Dynamic metadata: generateMetadata
When the title depends on data, such as a blog post or product:
// app/blog/[slug]/page.tsx
import type { Metadata } from 'next';
export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
const { slug } = await params;
const post = await getPost(slug);
return {
title: post.title,
description: post.excerpt,
openGraph: { images: [post.coverImage] },
};
}
export default async function Page({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params;
const post = await getPost(slug); // same request as generateMetadata, fetched once if you cache getPost
return <article><h1>{post.title}</h1></article>;
}File-based metadata
Drop special files into app/ and Next.js wires them up:
| File | Generates |
|---|---|
favicon.ico, icon.png, apple-icon.png |
Browser and app icons |
opengraph-image.png (or .tsx to generate one with code) |
Social sharing images |
robots.ts |
/robots.txt |
sitemap.ts |
/sitemap.xml |
// app/sitemap.ts
import type { MetadataRoute } from 'next';
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const posts = await getAllPosts();
return [
{ url: 'https://learntocode.example', lastModified: new Date() },
...posts.map((p) => ({ url: `https://learntocode.example/blog/${p.slug}`, lastModified: p.updatedAt })),
];
}Not found: notFound() and not-found.tsx
// app/blog/[slug]/page.tsx
import { notFound } from 'next/navigation';
export default async function Page({ params }: { params: Promise<{ slug: string }> }) {
const post = await getPost((await params).slug);
if (!post) notFound(); // renders the nearest not-found.tsx with a 404 status
return <h1>{post.title}</h1>;
}// app/not-found.tsx
import Link from 'next/link';
export default function NotFound() {
return (
<div>
<h2>Page not found</h2>
<Link href="/">Go home</Link>
</div>
);
}Errors: error.tsx
An error.tsx file creates an error boundary for its route segment. If anything in that segment throws, this UI replaces it, while the rest of the app (layouts above it) keeps working. Error boundaries must be Client Components:
// app/dashboard/error.tsx
'use client';
import { useEffect } from 'react';
export default function ErrorPage({
error,
retry,
}: {
error: Error & { digest?: string };
retry: () => void;
}) {
useEffect(() => {
console.error(error); // send to Sentry or another error tracker
}, [error]);
return (
<div>
<h2>Something went wrong!</h2>
<button onClick={() => retry()}>Try again</button>
</div>
);
}retry()re-fetches and re-renders the segment. (Areset()function also exists, for the rarer case of re-rendering without re-fetching.)- Errors bubble up to the nearest
error.tsx. Place them at different levels for granular recovery. app/global-error.tsxcatches errors in the root layout. It must render its own<html>and<body>.- In production, server error messages are hidden from users. The
digestlets you match the error in your server logs.
Here's the error-boundary idea, live:
Proxy (formerly Middleware)
Proxy runs code before a request is completed. It can redirect, rewrite, or set headers based on the incoming request. Starting with Next.js 16, the file is called proxy.ts (it used to be middleware.ts) and lives in the project root, next to app/:
// proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function proxy(request: NextRequest) {
const session = request.cookies.get('session');
// Optimistic check: send signed-out users to the login page
if (!session && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url));
}
const response = NextResponse.next();
response.headers.set('x-powered-by-lesson', 'learn-to-code');
return response;
}
export const config = {
matcher: ['/dashboard/:path*', '/account/:path*'], // only run on these paths
};Good uses: redirects based on cookies or location, A/B-test rewrites, adding security headers, and locale detection.
⚠️ Proxy is for fast, optimistic checks. It is not a full authorization solution, and not the place for slow data fetching. Always verify the user again where the data is accessed (in Server Components, Server Actions and Route Handlers). For simple static redirects, use
redirectsinnext.config.tsinstead.
Practice (in your project)
- Add a root
metadatawith a title template, and give three pages their own titles. - Add
generateMetadatato a dynamic blog page. - Create
app/sitemap.tsandapp/robots.ts, then visit/sitemap.xml. - Add an
error.tsxto/dashboardand throw an error in its page to test it. - Write a
proxy.tsthat redirects/old-blog/*to/blog/*.
1.In Next.js 16, what is Middleware called and where does it live?
2.Why must error.tsx be a Client Component?