Next.js course Β· Module 2: Routing and Layouts

Nested Paths and Catch-All Parameters

15 min read Β·
In this lesson10

In the Quantum Metropolis, the transportation system enables residents to reach every corner of the city, and even unexplored territories. Special Q-Hopper vehicles can collect multiple travel destinations and visit them all in sequence, dynamically adapting to passenger needs. This flexibility is key to the functioning of such an advanced urban structure.

In the world of Next.js 16, similar flexibility is provided by advanced routing features such as nested paths and catch-all parameters. They allow handling complex URL structures and dynamic route generation based on data.

Dynamic Nested Paths

In Next.js 16, we can create nested dynamic paths by combining static and dynamic segments at different levels of the hierarchy:

app/
  β”œβ”€β”€ destinations/              # /destinations
  β”‚   β”œβ”€β”€ page.tsx               # Destinations list page
  β”‚   └── [destinationId]/       # Dynamic segment for destination ID
  β”‚       β”œβ”€β”€ page.tsx           # /destinations/:destinationId
  β”‚       └── attractions/       # /destinations/:destinationId/attractions
  β”‚           β”œβ”€β”€ page.tsx       # Attractions page for the destination
  β”‚           └── [attractionId] # Nested dynamic segment
  β”‚               └── page.tsx   # /destinations/:destinationId/attractions/:attractionId

In this structure, we have two levels of dynamic segments: [destinationId] and [attractionId]. This allows creating paths such as /destinations/mars/attractions/olympus-mons.

Implementing Dynamic Nested Paths

Here's an example of how to implement a nested paths system for our Quantum Voyages application:

// app/destinations/[destinationId]/page.tsx
import { getDestinationById } from '@/lib/api';
import { DestinationDetails } from '@/components/destinations/DestinationDetails';
import { AttractionsPreview } from '@/components/destinations/AttractionsPreview';
import Link from 'next/link';
import { notFound } from 'next/navigation';

// Generating static parameters for the most popular destinations
export async function generateStaticParams() {
  // Fetch the most popular destinations for prerendering
  const destinations = await getPopularDestinations();

  return destinations.map((destination) => ({
    destinationId: destination.id,
  }));
}

export default async function DestinationPage({ params }: { params: Promise<{ destinationId: string }> }) {
  const { destinationId } = await params;
  const destination = await getDestinationById(destinationId);

  // If the destination doesn't exist, show the 404 page
  if (!destination) {
    notFound();
  }

  return (
    <div className="container mx-auto px-4 py-12">
      <h1 className="text-4xl font-bold mb-6">{destination.name}</h1>

      <DestinationDetails destination={destination} />

      <section className="mt-12">
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-2xl font-semibold">Popular Attractions</h2>
          <Link
            href={`/destinations/${destinationId}/attractions`}
            className="text-indigo-600 hover:underline"
          >
            See all attractions
          </Link>
        </div>

        <AttractionsPreview destinationId={destinationId} />
      </section>
    </div>
  );
}
// app/destinations/[destinationId]/attractions/page.tsx
import { getDestinationById, getAttractionsForDestination } from '@/lib/api';
import Link from 'next/link';
import Image from 'next/image';
import { notFound } from 'next/navigation';

export default async function DestinationAttractionsPage({ params }: { params: Promise<{ destinationId: string }> }) {
  const { destinationId } = await params;
  const destination = await getDestinationById(destinationId);

  if (!destination) {
    notFound();
  }

  const attractions = await getAttractionsForDestination(destinationId);

  return (
    <div className="container mx-auto px-4 py-12">
      <div className="flex items-center gap-2 mb-8 text-sm text-gray-500">
        <Link href="/destinations" className="hover:text-indigo-600">Destinations</Link>
        <span>/</span>
        <Link href={`/destinations/${destinationId}`} className="hover:text-indigo-600">
          {destination.name}
        </Link>
        <span>/</span>
        <span>Attractions</span>
      </div>

      <h1 className="text-3xl font-bold mb-2">Attractions at {destination.name}</h1>
      <p className="text-gray-600 mb-8">{destination.description}</p>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
        {attractions.map((attraction) => (
          <Link
            key={attraction.id}
            href={`/destinations/${destinationId}/attractions/${attraction.id}`}
            className="block group"
          >
            <div className="rounded-lg overflow-hidden shadow-md hover:shadow-lg transition-shadow">
              <div className="relative h-48">
                <Image
                  src={attraction.imageUrl}
                  alt={attraction.name}
                  fill
                  className="object-cover transition-transform group-hover:scale-105"
                />
              </div>
              <div className="p-4">
                <h2 className="text-xl font-semibold mb-2">{attraction.name}</h2>
                <p className="text-gray-600 line-clamp-2">{attraction.shortDescription}</p>
              </div>
            </div>
          </Link>
        ))}
      </div>
    </div>
  );
}
// app/destinations/[destinationId]/attractions/[attractionId]/page.tsx
import { getDestinationById, getAttractionById } from '@/lib/api';
import Link from 'next/link';
import Image from 'next/image';
import { notFound } from 'next/navigation';

export default async function AttractionPage({
  params
}: {
  params: Promise<{ destinationId: string; attractionId: string }>
}) {
  const { destinationId, attractionId } = await params;

  const [destination, attraction] = await Promise.all([
    getDestinationById(destinationId),
    getAttractionById(destinationId, attractionId)
  ]);

  if (!destination || !attraction) {
    notFound();
  }

  return (
    <div className="container mx-auto px-4 py-12">
      <div className="flex items-center gap-2 mb-8 text-sm text-gray-500">
        <Link href="/destinations" className="hover:text-indigo-600">Destinations</Link>
        <span>/</span>
        <Link href={`/destinations/${destinationId}`} className="hover:text-indigo-600">
          {destination.name}
        </Link>
        <span>/</span>
        <Link href={`/destinations/${destinationId}/attractions`} className="hover:text-indigo-600">
          Attractions
        </Link>
        <span>/</span>
        <span>{attraction.name}</span>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
        <div className="relative h-[400px] lg:h-[600px] rounded-lg overflow-hidden">
          <Image
            src={attraction.imageUrl}
            alt={attraction.name}
            fill
            className="object-cover"
            preload
          />
        </div>

        <div>
          <h1 className="text-4xl font-bold mb-4">{attraction.name}</h1>
          <div className="flex items-center mb-6">
            <span className="px-3 py-1 bg-indigo-100 text-indigo-800 rounded-full text-sm">
              {attraction.category}
            </span>
            <span className="mx-4 text-gray-300">|</span>
            <div className="flex items-center text-amber-500">
              {/* Rating stars */}
              {Array.from({ length: 5 }).map((_, i) => (
                <svg key={i} xmlns="http://www.w3.org/2000/svg" className={`h-5 w-5 ${i < attraction.rating ? 'fill-current' : 'text-gray-300'}`} viewBox="0 0 20 20" fill="currentColor">
                  <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                </svg>
              ))}
              <span className="ml-2 text-gray-700">{attraction.rating.toFixed(1)}</span>
            </div>
          </div>

          <p className="text-gray-700 mb-6">{attraction.description}</p>

          <div className="space-y-4 mb-8">
            <div className="flex">
              <div className="w-32 font-semibold">Location:</div>
              <div>{attraction.location}</div>
            </div>
            <div className="flex">
              <div className="w-32 font-semibold">Visiting Cost:</div>
              <div>{attraction.price} credits</div>
            </div>
            <div className="flex">
              <div className="w-32 font-semibold">Visiting Time:</div>
              <div>{attraction.duration}</div>
            </div>
          </div>

          <button className="w-full py-3 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors">
            Book a Visit
          </button>
        </div>
      </div>
    </div>
  );
}

Catch-All Parameters

In the Quantum Metropolis, Q-Route technology enables traveling to any number of places based on a single route code. Similarly, in Next.js 16, catch-all parameters enable handling paths with any number of segments.

Catch-All Parameter Syntax

Catch-all parameters are denoted by three dots before the parameter name in square brackets:

[...param]

This notation allows matching any number of URL segments, which are passed as an array to the component.

Directory Structure

app/
  β”œβ”€β”€ shop/                   # /shop
  β”‚   └── [...categories]/    # /shop/category1
  β”‚       └── page.tsx        # /shop/category1/category2/category3/etc.

In this example, the path /shop/clothing/men/shirts will be matched by [...categories] and the categories parameter will contain the array ['clothing', 'men', 'shirts'].

Implementation for Quantum Voyages

Implementation of a product category system with catch-all parameters:

// app/shop/[...categories]/page.tsx
import { fetchCategorizedProducts } from '@/lib/api/products';
import { Breadcrumbs } from '@/components/shop/Breadcrumbs';
import { ProductGrid } from '@/components/shop/ProductGrid';
import { CategoryFilters } from '@/components/shop/CategoryFilters';

export default async function CategoriesPage({ params }: { params: Promise<{ categories: string[] }> }) {
  const { categories } = await params;

  // Fetching products based on all provided categories
  const { products, availableFilters } = await fetchCategorizedProducts(categories);

  // Constructing the title based on the last category
  const currentCategory = categories[categories.length - 1];
  const formattedCategoryName = currentCategory
    .split('-')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');

  return (
    <div className="container mx-auto px-4 py-12">
      <Breadcrumbs categories={categories} />

      <h1 className="text-3xl font-bold mb-8">{formattedCategoryName}</h1>

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
        <div className="lg:col-span-1">
          <CategoryFilters
            categories={categories}
            availableFilters={availableFilters}
          />
        </div>

        <div className="lg:col-span-3">
          <ProductGrid products={products} />
        </div>
      </div>
    </div>
  );
}

Helper Components

// components/shop/Breadcrumbs.tsx
import Link from 'next/link';

export function Breadcrumbs({ categories }: { categories: string[] }) {
  return (
    <div className="flex items-center flex-wrap gap-2 mb-8 text-sm text-gray-500">
      <Link href="/shop" className="hover:text-indigo-600">
        Shop
      </Link>

      {categories.map((category, index) => {
        // Building the URL path for this category
        const url = `/shop/${categories.slice(0, index + 1).join('/')}`;
        const isLast = index === categories.length - 1;

        const formattedName = category
          .split('-')
          .map(word => word.charAt(0).toUpperCase() + word.slice(1))
          .join(' ');

        return (
          <div key={category} className="flex items-center">
            <span className="mx-2">/</span>
            {isLast ? (
              <span>{formattedName}</span>
            ) : (
              <Link href={url} className="hover:text-indigo-600">
                {formattedName}
              </Link>
            )}
          </div>
        );
      })}
    </div>
  );
}

Optional Catch-All Parameters

In Next.js 16, we can also define optional catch-all parameters using double square brackets:

[[...param]]

The main difference is that an optional catch-all parameter will also match the path without any segments. For example, app/shop/[[...categories]]/page.tsx will match:

  • /shop (here categories is missing, i.e. undefined, which is why the code below uses || [])
  • /shop/clothing (categories = ['clothing'])
  • /shop/clothing/men/shirts (categories = ['clothing', 'men', 'shirts'])

Implementing a Shop with Optional Catch-All Parameters

// app/shop/[[...categories]]/page.tsx
import { fetchCategorizedProducts, fetchFeaturedProducts } from '@/lib/api/products';
import { Breadcrumbs } from '@/components/shop/Breadcrumbs';
import { ProductGrid } from '@/components/shop/ProductGrid';
import { CategoryFilters } from '@/components/shop/CategoryFilters';
import { FeaturedProducts } from '@/components/shop/FeaturedProducts';
import { CategoryPreview } from '@/components/shop/CategoryPreview';

export default async function ShopPage({ params }: { params: Promise<{ categories?: string[] }> }) {
  const categories = (await params).categories || [];
  const isRootShopPage = categories.length === 0;

  if (isRootShopPage) {
    // We're on the main shop page
    const featuredProducts = await fetchFeaturedProducts();
    const topCategories = await fetchTopCategories();

    return (
      <div className="container mx-auto px-4 py-12">
        <h1 className="text-4xl font-bold mb-12">Shop Quantum Voyages</h1>

        <section className="mb-16">
          <h2 className="text-2xl font-semibold mb-8">Featured Products</h2>
          <FeaturedProducts products={featuredProducts} />
        </section>

        <section>
          <h2 className="text-2xl font-semibold mb-8">Browse Categories</h2>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
            {topCategories.map(category => (
              <CategoryPreview key={category.id} category={category} />
            ))}
          </div>
        </section>
      </div>
    );
  } else {
    // We're on a category page
    const { products, availableFilters } = await fetchCategorizedProducts(categories);

    // Constructing the title based on the last category
    const currentCategory = categories[categories.length - 1];
    const formattedCategoryName = currentCategory
      .split('-')
      .map(word => word.charAt(0).toUpperCase() + word.slice(1))
      .join(' ');

    return (
      <div className="container mx-auto px-4 py-12">
        <Breadcrumbs categories={categories} />

        <h1 className="text-3xl font-bold mb-8">{formattedCategoryName}</h1>

        <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
          <div className="lg:col-span-1">
            <CategoryFilters
              categories={categories}
              availableFilters={availableFilters}
            />
          </div>

          <div className="lg:col-span-3">
            <ProductGrid products={products} />
          </div>
        </div>
      </div>
    );
  }
}

Accessing Parameters in Components

In Next.js 16, we can access path parameters in several ways:

In Server Components

// Server Component
export default async function ProductPage({ params }: { params: Promise<{ productId: string }> }) {
  // Using (await params).productId
  return <div>Product ID: {(await params).productId}</div>;
}

In Client Components

In client-side components, we can use the useParams hook from next/navigation:

'use client';

import { useParams } from 'next/navigation';

export default function ClientProductDetails() {
  const params = useParams();
  const productId = params.productId;

  return <div>Viewing product: {productId}</div>;
}

In Generation Functions

Next.js 16 offers functions for generating static parameters and metadata:

// Generating static parameters
export async function generateStaticParams() {
  const products = await fetchTopProducts();

  return products.map((product) => ({
    productId: product.id,
  }));
}

// Generating metadata
export async function generateMetadata({ params }: { params: Promise<{ productId: string }> }) {
  const product = await fetchProductById((await params).productId);

  return {
    title: product.name,
    description: product.description,
    openGraph: {
      images: [{ url: product.imageUrl }],
    },
  };
}

Parameter Validation and Handling

When working with dynamic parameters, it's important to validate them:

export default async function ProductPage({ params }: { params: Promise<{ productId: string }> }) {
  // Check if productId is a valid UUID
  if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test((await params).productId)) {
    // Throw an error that will be caught by the nearest error.js
    throw new Error('Invalid product ID format');
  }

  const product = await fetchProductById((await params).productId);

  // If the product doesn't exist, show the 404 page
  if (!product) {
    notFound();
  }

  return <ProductDetails product={product} />;
}

Error and Missing Resource Handling

Next.js 16 enables elegant handling of situations when a resource is not found or an error occurs:

Error Handling with error.js

The error.tsx file must be a Client Component (the 'use client' directive): an error boundary in React relies on lifecycle methods that exist only in the browser, and the button with reset() needs a click handler.

// app/products/[productId]/error.tsx
'use client';

import { useEffect } from 'react';

export default function ProductError({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  useEffect(() => {
    // You can log the error to an external service
    console.error(error);
  }, [error]);

  return (
    <div className="container mx-auto px-4 py-16 text-center">
      <h2 className="text-2xl font-bold mb-4">Something went wrong!</h2>
      <p className="mb-8 text-gray-600">{error.message}</p>
      <button
        onClick={reset}
        className="px-4 py-2 bg-indigo-600 text-white rounded hover:bg-indigo-700"
      >
        Try again
      </button>
    </div>
  );
}

Missing Resource Handling with not-found.js

// app/products/[productId]/not-found.tsx
import Link from 'next/link';

export default function ProductNotFound() {
  return (
    <div className="container mx-auto px-4 py-16 text-center">
      <h2 className="text-3xl font-bold mb-4">Product Not Found</h2>
      <p className="mb-8 text-gray-600">
        Sorry, we couldn't find the product you're looking for.
      </p>
      <Link
        href="/products"
        className="px-4 py-2 bg-indigo-600 text-white rounded hover:bg-indigo-700"
      >
        Back to all products
      </Link>
    </div>
  );
}

Example: Advanced Documentation System

In the Quantum Metropolis, an interactive documentation system allows navigating through complex information hierarchies. Let's implement a similar system in Next.js 16:

app/
  β”œβ”€β”€ docs/
  β”‚   └── [[...slug]]/     # Optional catch-all
  β”‚       └── page.tsx     # /docs, /docs/guides, /docs/guides/routing, etc.
// app/docs/[[...slug]]/page.tsx
import { fetchDocumentBySlug, fetchDocCategories } from '@/lib/api/documentation';
import { DocSidebar } from '@/components/docs/DocSidebar';
import { DocContent } from '@/components/docs/DocContent';
import { DocBreadcrumbs } from '@/components/docs/DocBreadcrumbs';
import { DocPagination } from '@/components/docs/DocPagination';
import { notFound } from 'next/navigation';

export default async function DocPage({ params }: { params: Promise<{ slug?: string[] }> }) {
  const slug = (await params).slug || [];
  const slugPath = slug.join('/');

  // Fetch documentation categories for the sidebar menu
  const categories = await fetchDocCategories();

  // If no path is provided, show the main documentation page
  if (slug.length === 0) {
    return (
      <div className="container mx-auto px-4 py-12">
        <div className="flex flex-col lg:flex-row gap-8">
          <DocSidebar categories={categories} currentSlug="" />

          <main className="flex-1">
            <h1 className="text-4xl font-bold mb-8">Quantum Voyages Documentation</h1>

            <div className="prose prose-indigo max-w-none">
              <p>
                Welcome to the Quantum Voyages documentation center. Here you'll find all the information
                needed to plan and take a space journey, from basic guides
                to advanced technical instructions.
              </p>

              <h2>Popular Sections</h2>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-6 not-prose">
                {categories.map(category => (
                  <div key={category.slug} className="border rounded-lg p-6 hover:shadow-md transition-shadow">
                    <h3 className="text-xl font-semibold mb-2">{category.title}</h3>
                    <p className="text-gray-600 mb-4">{category.description}</p>
                    <a href={`/docs/${category.slug}`} className="text-indigo-600 hover:underline">
                      Overviewaj {category.title.toLowerCase()} β†’
                    </a>
                  </div>
                ))}
              </div>
            </div>
          </main>
        </div>
      </div>
    );
  }

  // Fetch document based on the path
  const document = await fetchDocumentBySlug(slugPath);

  // If the document doesn't exist, show the 404 page
  if (!document) {
    notFound();
  }

  // Fetch previous and next documents for navigation
  const { previousDoc, nextDoc } = await fetchAdjacentDocs(slugPath);

  return (
    <div className="container mx-auto px-4 py-12">
      <DocBreadcrumbs slug={slug} />

      <div className="flex flex-col lg:flex-row gap-8">
        <DocSidebar categories={categories} currentSlug={slugPath} />

        <main className="flex-1">
          <h1 className="text-4xl font-bold mb-8">{document.title}</h1>

          <DocContent content={document.content} />

          <DocPagination previousDoc={previousDoc} nextDoc={nextDoc} />
        </main>
      </div>
    </div>
  );
}

// Generating static parameters for popular documentation paths
export async function generateStaticParams() {
  const popularDocs = await fetchPopularDocs();

  return popularDocs.map(doc => ({
    slug: doc.slug.split('/'),
  }));
}

Combining Catch-All Parameters with Other Features

Next.js 16 allows combining catch-all parameters with other advanced routing features:

1. Grouping Routes with Catch-All Parameters

app/
  β”œβ”€β”€ (dashboard)/
  β”‚   └── admin/
  β”‚       └── users/
  β”‚           └── [...roles]/    # /admin/users/admin/editor/etc.
  β”‚               └── page.tsx

2. Intercepting Routes with Catch-All Parameters

// app/(shop)/products/@modal/(.)[...categories]/page.tsx
// Intercepts /products/category1/category2 as a modal during navigation from /products.
// A catch-all segment must be the last one in the path: [productId] cannot come after [...categories].

3. Parallel Routes with Catch-All Parameters

app/
  β”œβ”€β”€ trips/
  β”‚   β”œβ”€β”€ page.tsx              # /trips
  β”‚   β”œβ”€β”€ @filters/
  β”‚   β”‚   β”œβ”€β”€ default.tsx       # Required in Next.js 16
  β”‚   β”‚   └── [...params]/      # Parallel route for filters
  β”‚   β”‚       └── page.tsx
  β”‚   └── @map/
  β”‚       β”œβ”€β”€ default.tsx       # Required in Next.js 16
  β”‚       └── [...location]/    # Parallel route for map
  β”‚           └── page.tsx

Advanced Navigation Variants with Parameters

'use client';

import { useRouter } from 'next/navigation';
import { useState } from 'react';

export function CategoryNavigator({ categories, subcategories }) {
  const router = useRouter();
  const [selectedCategoryId, setSelectedCategoryId] = useState('');

  const handleCategoryChange = (categoryId) => {
    setSelectedCategoryId(categoryId);
    const selectedCategory = categories.find(c => c.id === categoryId);
    router.push(`/shop/${selectedCategory.slug}`);
  };

  const handleSubcategoryChange = (categoryId, subcategoryId) => {
    const selectedCategory = categories.find(c => c.id === categoryId);
    const selectedSubcategory = subcategories.find(sc => sc.id === subcategoryId);
    router.push(`/shop/${selectedCategory.slug}/${selectedSubcategory.slug}`);
  };

  return (
    <div className="space-y-4">
      <div>
        <label className="block mb-2 text-sm font-medium">Category</label>
        <select
          className="w-full p-2 border rounded"
          onChange={(e) => handleCategoryChange(e.target.value)}
        >
          <option value="">Select a category</option>
          {categories.map(category => (
            <option key={category.id} value={category.id}>
              {category.name}
            </option>
          ))}
        </select>
      </div>

      <div>
        <label className="block mb-2 text-sm font-medium">Subcategory</label>
        <select
          className="w-full p-2 border rounded"
          onChange={(e) => handleSubcategoryChange(selectedCategoryId, e.target.value)}
        >
          <option value="">Select a subcategory</option>
          {/* Subcategory options */}
        </select>
      </div>
    </div>
  );
}

Advanced Search with Catch-All Parameters

// app/search/[[...query]]/page.tsx
import { searchProducts } from '@/lib/api/search';

export default async function SearchPage({
  params,
  searchParams,
}: {
  params: Promise<{ query?: string[] }>;
  searchParams: Promise<{ category?: string; sort?: string; filters?: string }>;
}) {
  const query = (await params).query || [];
  const searchTerm = query.join(' ');

  // Fetching query parameters
  const { category, sort, filters } = await searchParams;

  // Performing the search
  const results = await searchProducts({
    searchTerm,
    category,
    sort,
    filters: filters ? JSON.parse(filters) : undefined
  });

  return (
    <div className="container mx-auto px-4 py-12">
      <h1 className="text-3xl font-bold mb-8">
        {searchTerm
          ? `Search results for: "${searchTerm}"`
          : 'Product Search'
        }
      </h1>

      {/* Search filters */}
      <SearchFilters
        initialCategory={category}
        initialSort={sort}
        initialFilters={filters ? JSON.parse(filters) : {}}
      />

      {/* Search results */}
      <SearchResults results={results} />
    </div>
  );
}

Summary

Nested dynamic paths and catch-all parameters in Next.js 16 offer an extremely flexible routing system that can handle virtually any navigation scenario in modern web applications:

  1. Nested dynamic parameters enable creating complex hierarchical URL structures, such as /destinations/:destinationId/attractions/:attractionId.

  2. Catch-all parameters ([...param]) allow matching any number of URL segments, which is ideal for documentation systems, product categories, and flexible search interfaces.

  3. Optional catch-all parameters ([[...param]]) additionally handle the case of no segments, allowing the use of the same component for the base path and all its subpaths.

  4. Error and missing resource handling through error.js and not-found.js files ensures an elegant user experience even when problems occur.

  5. Parameter validation prevents errors and ensures application security.

By combining these techniques with features like static parameter generation (generateStaticParams), we can create efficient, dynamic, and easy-to-maintain navigation systems for applications of any scale and complexity.

In the next lesson you will see how layouts and loading.tsx files form the permanent infrastructure of pages.

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Route Groups in App Router are marked using:

  2. 2. Catch-all segments in App Router are created using:

Hands-on tasks in the game

  • Code editor

    Create the file error.js: start with the 'use client' directive (error.js must be a Client Component), then write the default-exported ErrorPage({ error, reset }) component. Show a friendly error message, e.g. an h2 heading β€œSomething went wrong!”, and a β€œTry again” button that calls reset() when clicked.

  • Vertical ordering

    Arrange the steps for creating a dynamic route in App Router

  • Click in order

    Arrange the default export syntax of a page component in Next.js

  • Code editor

    Create a Client Component Counter (default export): the file starts with 'use client', you create the count state with useState(0), display it in a p paragraph, and a β€œ+1” button increases the counter by 1 on every click.

  1. QuestionRoute Groups in App Router
  2. QuestionCatch-All Segments
  3. Coding taskPractice: Error Handling with error.js
  4. Put in orderCreating a Dynamic Route
  5. Click in orderPage Component Export
  6. Coding taskPractice: Client Component with Counter

Useful articles