Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

NX
Next.js
0/10 completed
Beginner
Why Next.js?Pages, layouts and routingLinks, images and fonts
Intermediate
Server and Client ComponentsFetching data and streamingRoute Handlers (API routes)Forms and Server Actions
Advanced
Caching and revalidationMetadata, SEO, errors and Proxy
Pro
Auth, deployment and production
Tracks / Next.js / Advanced

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):

tsx
// 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' },
};
tsx
// 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:

tsx
// 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
ts
// 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

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>;
}
tsx
// 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:

tsx
// 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. (A reset() 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.tsx catches errors in the root layout. It must render its own <html> and <body>.
  • In production, server error messages are hidden from users. The digest lets 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/:

ts
// 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 redirects in next.config.ts instead.

Practice (in your project)

  1. Add a root metadata with a title template, and give three pages their own titles.
  2. Add generateMetadata to a dynamic blog page.
  3. Create app/sitemap.ts and app/robots.ts, then visit /sitemap.xml.
  4. Add an error.tsx to /dashboard and throw an error in its page to test it.
  5. Write a proxy.ts that redirects /old-blog/* to /blog/*.
✎ Check your understanding

1.In Next.js 16, what is Middleware called and where does it live?

2.Why must error.tsx be a Client Component?

← Caching and revalidation
React · live preview
Preview