Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

Next.js App Router: Layouts, Routing and Data Fetching

The App Router combines route segments, rendering boundaries and data access. Using a product catalog, this guide explains how to keep interactive code small, choose explicit freshness policies, stream slow content and handle failures without unnecessary client-side requests.

Published Updated Written by Reading time 8 min read
On this page Contents: quick navigation between sections

File-based routing and shared layouts

app/layout.tsx

import type { ReactNode } from "react";
import Link from "next/link";

interface RootLayoutProps {
  children: ReactNode;
}

export default function RootLayout({ children }: RootLayoutProps) {
  return (
    <html lang="en">
      <body>
        <header>
          <nav aria-label="Main navigation">
            <Link href="/en">Home</Link>
            <Link href="/en/products">Products</Link>
          </nav>
        </header>

        <main>{children}</main>
      </body>
    </html>
  );
}

app/page.tsx

export default function HomePage() {
  return <h1>Product catalog</h1>;
}

app/page.tsx serves /, and app/products/page.tsx serves /products. A directory alone does not expose a page. The root layout contains html and body; nested layouts wrap their segments without repeating shared navigation. [1]

Link enables client-side navigation and may prefetch route data. A shared layout typically preserves state across navigation within its subtree, so do not assume its logic reruns on every URL change. Route groups such as (shop) organize files without adding URL segments. [1][14]

Dynamic routes, parameters and static generation

lib/catalog.ts

import "server-only";

export interface Product {
  slug: string;
  name: string;
  priceInCents: number;
}

const products: readonly Product[] = [
  { slug: "keyboard", name: "Keyboard", priceInCents: 8900 },
  { slug: "mouse", name: "Mouse", priceInCents: 3900 },
];

export function listProducts(): readonly Product[] {
  return products.map((product) => ({ ...product }));
}

export function findProduct(slug: string): Product | undefined {
  const product = products.find((entry) => entry.slug === slug);
  return product ? { ...product } : undefined;
}

app/products/[slug]/page.tsx

import { notFound } from "next/navigation";
import { findProduct, listProducts } from "../../../lib/catalog";
import FavoriteButton from "./favorite-button";

interface ProductPageProps {
  params: Promise<{ slug: string }>;
}

export function generateStaticParams() {
  return listProducts().map(({ slug }) => ({ slug }));
}

export default async function ProductPage({ params }: ProductPageProps) {
  const { slug } = await params;
  const product = findProduct(slug);

  if (!product) {
    notFound();
  }

  const price = new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
  }).format(product.priceInCents / 100);

  return (
    <article>
      <h1>{product.name}</h1>
      <p>{price}</p>
      <FavoriteButton key={product.slug} productName={product.name} />
    </article>
  );
}

app/products/page.tsx

import Link from "next/link";
import { listProducts } from "../../lib/catalog";

export default function ProductsPage() {
  const products = listProducts();

  return (
    <section>
      <h1>Products</h1>
      <ul>
        {products.map(({ slug, name }) => (
          <li key={slug}>
            <Link href={`/products/${slug}`}>{name}</Link>
          </li>
        ))}
      </ul>
    </section>
  );
}

The [slug] directory represents one URL segment. In the current API params is a promise, so an asynchronous page awaits it. For a missing product, notFound() stops rendering the segment instead of producing an empty product page. [2][10]

generateStaticParams supplies known parameters for build-time prerendering; it does not by itself forbid other URLs. The example uses a local catalog; later sections demonstrate a remote API. In a deployed application, list, detail and metadata reads must use the same authoritative data and identifiers. [2]

Server Components and Client Components

app/products/[slug]/favorite-button.tsx

"use client";

import { useState } from "react";

interface FavoriteButtonProps {
  productName: string;
}

export default function FavoriteButton({ productName }: FavoriteButtonProps) {
  const [isFavorite, setIsFavorite] = useState(false);

  return (
    <button
      type="button"
      aria-label={`Favorite: ${productName}`}
      aria-pressed={isFavorite}
      onClick={() => setIsFavorite((previous) => !previous)}
    >
      Favorite
    </button>
  );
}

Pages and layouts are Server Components by default. They can read databases and server configuration without shipping that logic to the browser. The use client directive marks a module-graph boundary, rather than disabling initial server HTML rendering. [3]

The favorite button needs state and onClick, so it is a small Client Component. Pass only serializable data required for rendering, never secrets. The button stores local state only; persistent favorites require a separate authorized mutation. [3][12]

Data fetching and explicit caching

lib/remote-catalog.ts

import "server-only";
import type { Product } from "./catalog";

function isProduct(value: unknown): value is Product {
  if (typeof value !== "object" || value === null) {
    return false;
  }

  const product = value as Record<string, unknown>;

  return (
    typeof product.slug === "string" &&
    /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(product.slug) &&
    typeof product.name === "string" &&
    product.name.trim().length > 0 &&
    typeof product.priceInCents === "number" &&
    Number.isSafeInteger(product.priceInCents) &&
    product.priceInCents >= 0
  );
}

export async function fetchProducts(): Promise<Product[]> {
  const apiUrl = process.env.CATALOG_API_URL;

  if (!apiUrl) {
    throw new Error("CATALOG_API_URL is not configured");
  }

  const response = await fetch(apiUrl, {
    next: { revalidate: 300 },
    signal: AbortSignal.timeout(10_000),
  });

  if (!response.ok) {
    throw new Error(`Catalog request failed: ${response.status}`);
  }

  const data: unknown = await response.json();

  if (!Array.isArray(data) || !data.every(isProduct)) {
    throw new Error("Invalid catalog response");
  }

  if (new Set(data.map(({ slug }) => slug)).size !== data.length) {
    throw new Error("Duplicate catalog slug");
  }

  return data.map(({ slug, name, priceInCents }) => ({
    slug,
    name,
    priceInCents,
  }));
}

With Cache Components disabled, the server-side fetch example uses next.revalidate: 300 for public catalog data. This is a revalidation window in seconds, not a guarantee of an update precisely every five minutes. cache: no-store bypasses persistent Data Cache, while force-cache opts in; avoid conflicting options. [5][6]

Set CATALOG_API_URL to a trusted endpoint returning an array with slug, name and priceInCents. Validate JSON before rendering and never use a user-supplied destination URL. With Cache Components enabled in Next.js 16 or later, use the separate use cache and cacheLife model and Suspense for request-time data; do not copy segment config mechanically. Never put private data in shared caches. [4][7][12][15]

The timeout covers fetching and reading the response body. Validation rejects blank names and duplicate slugs.

Streaming and Suspense boundaries

app/remote-products/page.tsx

import { Suspense } from "react";
import { fetchProducts } from "../../lib/remote-catalog";

async function ProductList() {
  const products = await fetchProducts();

  if (products.length === 0) {
    return <p>No products available.</p>;
  }

  return (
    <ul>
      {products.map((product) => (
        <li key={product.slug}>
          {product.name}
        </li>
      ))}
    </ul>
  );
}

export default function RemoteProductsPage() {
  return (
    <section>
      <h1>Products</h1>

      <Suspense fallback={<p role="status">Loading products...</p>}>
        <ProductList />
      </Suspense>
    </section>
  );
}

Move the await into a component below a Suspense boundary so slow data does not block the surrounding heading. loading.tsx creates a broader segment boundary, whereas Suspense allows a more targeted fallback. [4][8]

The remote example is independent of the local catalog: it uses /remote-products and does not link to local records. In production, lists, details and metadata should use one authoritative data source. [4]

Errors, missing resources and recovery

app/remote-products/error.tsx

"use client";

interface ProductsErrorProps {
  reset: () => void;
}

export default function ProductsError({ reset }: ProductsErrorProps) {
  return (
    <section aria-labelledby="products-error-title">
      <h2 id="products-error-title">Products could not be loaded</h2>
      <p role="alert">Please try again.</p>

      <button type="button" onClick={reset}>
        Retry
      </button>
    </section>
  );
}

app/products/[slug]/not-found.tsx

import Link from "next/link";

export default function ProductNotFound() {
  return (
    <section>
      <h1>Product not found</h1>
      <Link href="/en/products">Back to products</Link>
    </section>
  );
}

An absent product is different from a failing API or malformed JSON. error.tsx is a Client Component providing a boundary for segment content; reset attempts to render that content again. It does not guarantee cache invalidation or repair the upstream service. [9][10]

Do not display raw server errors. A segment boundary cannot catch errors in its own layout, which require an ancestor boundary. not-found.tsx provides a dedicated view; after streaming has started the HTTP status may already be 200, while Next.js signals the missing page through noindex. [8][9][10]

Route Handlers and security

app/api/products/route.ts

import { listProducts } from "../../../lib/catalog";

export function GET() {
  const products = listProducts();

  return Response.json(products);
}

app/api/products/route.ts exposes GET /api/products. Route Handlers use standard Request and Response APIs, and GET handler responses are not cached by default. A page and route file cannot coexist in the same segment. [11]

Server Components should generally call the data layer directly rather than send HTTP requests to their own handler. This example intentionally exposes a public catalog; private reads require session and permission checks at each access. A hidden button, layout or Server Component is not an authorization check. [12]

Metadata, SEO and indexing

app/products/[slug]/page.tsx

// Add this export to app/products/[slug]/page.tsx.
import type { Metadata } from "next";

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const { slug } = await params;
  const product = findProduct(slug);

  if (!product) {
    return { title: "Product not found" };
  }

  return {
    title: `${product.name} | Catalog`,
    description: `Details and price for ${product.name}.`,
  };
}

generateMetadata derives title and description from the same source as the page. Add the export to the detail page and reuse its existing findProduct import instead of duplicating it. App Router metadata is supported in Server Components. [13]

Use stable URLs, canonical URLs for duplicates, a sitemap and accessible links for a real catalog. Server Components do not guarantee search rankings; inspect production HTML, HTTP statuses, metadata and navigation behavior. Write descriptions using actual product content rather than filler. [13][14]

Check valid and empty responses, duplicate slugs, malformed JSON, HTTP 500, timeouts and missing products. Verify caching after next build and next start. [6][9][10]

Keep public data, request-specific data and interactive state separate. Shared layouts establish the shell, Server Components read data, and small Client Components handle interaction. Explicit cache policies and error boundaries make the application easier to evolve without depending on implicit defaults.

Next.js App Router React Server Components Routing Data Fetching Suspense Caching SEO TypeScript

Frequently asked questions

Does App Router replace Pages Router?

Both are supported; App Router uses app, nested layouts and Server Components. [1][3]

Does use client disable SSR?

No. It defines a client module boundary; initial HTML can still be server-rendered. [3]

Is fetch always cached?

No. Behavior depends on options, context and configuration; choose a policy and distinguish Cache Components. [5][6][7]

When should I use Route Handlers?

Use them for HTTP interfaces consumed by clients or other systems. Server Components can usually read the data layer directly. [11][12]

Sources and references

  1. Next.js, Layouts and Pages↩1↩2↩3↩4
  2. Next.js, Dynamic Segments↩1↩2↩3
  3. Next.js, Server and Client Components↩1↩2↩3↩4↩5
  4. Next.js, Fetching Data↩1↩2↩3
  5. Next.js, fetch↩1↩2↩3
  6. Next.js, Caching (Previous Model)↩1↩2↩3
  7. Next.js, Migrating to Cache Components↩1↩2↩3
  8. Next.js, loading.js↩1↩2
  9. Next.js, error.js↩1↩2↩3
  10. Next.js, notFound↩1↩2↩3↩4
  11. Next.js, Route Handlers↩1↩2
  12. Next.js, Authentication↩1↩2↩3↩4↩5
  13. Next.js, generateMetadata↩1↩2
  14. Next.js, Linking and Navigating↩1↩2
  15. Next.js, Revalidating↩

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning