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

Dynamic Path Segments and Parameters

17 min read Β·
In this lesson7

In the Quantum Metropolis, the most advanced transportation system possesses a remarkable ability to adapt to the needs of its citizens. Transport routes are not rigidly defined - they can dynamically reorganize to guide travelers to any location in the city. This flexibility is key to the efficient functioning of such a complex urban organism.

In the world of Next.js 16, dynamic path segments serve an analogous function, allowing you to create routes that adapt to different parameters and contexts. They are what make navigation in an application truly interactive and tailored to the user's needs.

Dynamic Segments in App Router

In Next.js 16, dynamic path segments are created by placing the parameter name in square brackets [param]. Such a folder will match different values in that URL segment, and the parameter value will be available inside the page components.

Basic Dynamic Segments

Here is what the file structure looks like for an application with dynamic segments:

app/
  β”œβ”€β”€ destinations/
  β”‚   β”œβ”€β”€ page.tsx               # matches /destinations
  β”‚   └── [planetId]/            # matches /destinations/:planetId (dynamic segment)
  β”‚       └── page.tsx           # matches /destinations/mars, /destinations/venus, etc.

In this example, [planetId] is a dynamic segment that can accept any value, e.g., "mars", "venus", or "jupiter". This value is then available in the page component through the params prop. In Next.js 16 params is a Promise, so you read it with const { planetId } = await params.

Implementing a Page with a Dynamic Segment

Let's look at the implementation of a page that uses the dynamic segment [planetId]:

// app/destinations/[planetId]/page.tsx
import Image from 'next/image';
import { notFound } from 'next/navigation';

// This type defines the parameter structure for this page
type PlanetPageParams = {
  params: Promise<{
    planetId: string;
  }>;
};

async function getPlanetData(planetId: string) {
  // Normally we would fetch data from an API or database here
  // For this example, we use static data
  const planets: Record<string, {
    name: string;
    description: string;
    gravity: string;
    diameter: string;
    dayLength: string;
    yearLength: string;
    temperature: string;
    imageUrl: string;
  }> = {
    'mars': {
      name: 'Mars',
      description: 'The Red Planet known for harsh conditions and fascinating geological phenomena.',
      gravity: '3.721 m/sΒ²',
      diameter: '6,779 km',
      dayLength: '24h 37m',
      yearLength: '687 Earth days',
      temperature: '-63Β°C (average)',
      imageUrl: '/images/mars.jpg'
    },
    'venus': {
      name: 'Venus',
      description: 'The second planet from the Sun, known for its extremely hot climate and dense atmosphere.',
      gravity: '8.87 m/sΒ²',
      diameter: '12,104 km',
      dayLength: '243 Earth days',
      yearLength: '225 Earth days',
      temperature: '462Β°C (average)',
      imageUrl: '/images/venus.jpg'
    },
    'jupiter': {
      name: 'Jupiter',
      description: 'The largest planet in the Solar System, known for the Great Red Spot and numerous moons.',
      gravity: '24.79 m/sΒ²',
      diameter: '139,820 km',
      dayLength: '9h 56m',
      yearLength: '11.86 Earth years',
      temperature: '-108Β°C (average)',
      imageUrl: '/images/jupiter.jpg'
    }
  };

  return planets[planetId];
}

// Component receives params as props
export default async function PlanetPage({ params }: PlanetPageParams) {
  // Fetching planet data based on planetId
  const planet = await getPlanetData((await params).planetId);

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

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

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
        <div className="relative h-96 lg:h-auto rounded-lg overflow-hidden">
          <Image
            src={planet.imageUrl}
            alt={planet.name}
            fill
            className="object-cover"
            preload
          />
        </div>

        <div className="space-y-6">
          <p className="text-lg text-gray-700">{planet.description}</p>

          <div className="bg-gray-50 p-6 rounded-lg shadow-sm">
            <h2 className="text-2xl font-semibold mb-4">Planetary Data</h2>
            <table className="w-full">
              <tbody>
                <tr className="border-b">
                  <th className="text-left py-2">Gravity</th>
                  <td className="text-right py-2">{planet.gravity}</td>
                </tr>
                <tr className="border-b">
                  <th className="text-left py-2">Diameter</th>
                  <td className="text-right py-2">{planet.diameter}</td>
                </tr>
                <tr className="border-b">
                  <th className="text-left py-2">Day Length</th>
                  <td className="text-right py-2">{planet.dayLength}</td>
                </tr>
                <tr className="border-b">
                  <th className="text-left py-2">Year Length</th>
                  <td className="text-right py-2">{planet.yearLength}</td>
                </tr>
                <tr>
                  <th className="text-left py-2">Temperature</th>
                  <td className="text-right py-2">{planet.temperature}</td>
                </tr>
              </tbody>
            </table>
          </div>

          <div className="flex space-x-4">
            <a
              href={`/destinations/${(await params).planetId}/colonies`}
              className="px-6 py-3 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors"
            >
              Colonies
            </a>
            <a
              href={`/destinations/${(await params).planetId}/tours`}
              className="px-6 py-3 border border-indigo-600 text-indigo-600 rounded-lg hover:bg-indigo-50 transition-colors"
            >
              Tours
            </a>
          </div>
        </div>
      </div>
    </div>
  );
}

In the code above:

  1. We define the PlanetPageParams type, which specifies the parameter structure received by the component
  2. The PlanetPage component receives a params object containing planetId from the URL
  3. We use this planetId to fetch data about the planet
  4. We display detailed information about the planet, as well as links to subpages that also use the same parameter

Generating Static Pages for Known Parameters

If we know in advance all possible values for a dynamic segment, we can generate static pages during the build process, which significantly improves performance. The generateStaticParams function serves this purpose:

// app/destinations/[planetId]/page.tsx

// This function defines the static paths that will be generated during the build
export async function generateStaticParams() {
  // Normally we would fetch data from an API or database here
  // We return an array of objects with parameters to be statically generated
  return [
    { planetId: 'mars' },
    { planetId: 'venus' },
    { planetId: 'jupiter' }
  ];
}

// Rest of the component...

Thanks to this, Next.js will generate three static pages during the build: for Mars, Venus, and Jupiter. This will significantly speed up their loading, as they won't need to be dynamically generated with each request.

Multi-Level Dynamic Segments

In the Quantum Metropolis, the transportation system enables traveling to any destination through a series of precise transfers, each narrowing the space to the selected target. Similarly in Next.js 16, we can create multi-level dynamic segments to precisely specify the requested resources.

Structure with Multiple Dynamic Segments

app/
  β”œβ”€β”€ destinations/
  β”‚   β”œβ”€β”€ [planetId]/           # matches /destinations/:planetId
  β”‚   β”‚   β”œβ”€β”€ page.tsx          # matches /destinations/mars
  β”‚   β”‚   └── [moonId]/         # matches /destinations/:planetId/:moonId
  β”‚   β”‚       └── page.tsx      # matches /destinations/mars/phobos
  β”‚   └── page.tsx              # matches /destinations

In this structure, we have two levels of dynamic segments:

  1. [planetId] - planet identifier
  2. [moonId] - moon identifier for the given planet

Implementing a Page with Nested Parameters

// app/destinations/[planetId]/[moonId]/page.tsx
import Image from 'next/image';
import Link from 'next/link';
import { notFound } from 'next/navigation';

type MoonPageParams = {
  params: Promise<{
    planetId: string;
    moonId: string;
  }>;
};

async function getMoonData(planetId: string, moonId: string) {
  // Moon-to-planet mapping system
  const moonData: Record<string, Record<string, {
    name: string;
    description: string;
    diameter: string;
    orbitDistance: string;
    discovered: string;
    imageUrl: string;
  }>> = {
    'mars': {
      'phobos': {
        name: 'Phobos',
        description: "The larger and closer of Mars's two natural satellites, orbiting the planet every 7 hours and 39 minutes.",
        diameter: '22.2 km',
        orbitDistance: '9,376 km',
        discovered: '1877',
        imageUrl: '/images/phobos.jpg'
      },
      'deimos': {
        name: 'Deimos',
        description: "The smaller and farther of Mars's two natural satellites, with an irregular shape.",
        diameter: '12.6 km',
        orbitDistance: '23,463 km',
        discovered: '1877',
        imageUrl: '/images/deimos.jpg'
      }
    },
    'jupiter': {
      'europa': {
        name: 'Europa',
        description: "Jupiter's moon that may harbor a subsurface ocean of water beneath its icy crust.",
        diameter: '3,121.6 km',
        orbitDistance: '670,900 km',
        discovered: '1610',
        imageUrl: '/images/europa.jpg'
      },
      'io': {
        name: 'Io',
        description: 'The most volcanically active object in the Solar System, with over 400 active volcanoes.',
        diameter: '3,643.2 km',
        orbitDistance: '421,700 km',
        discovered: '1610',
        imageUrl: '/images/io.jpg'
      },
      'ganymede': {
        name: 'Ganymede',
        description: 'The largest moon in the Solar System, even larger than the planet Mercury.',
        diameter: '5,268.2 km',
        orbitDistance: '1,070,400 km',
        discovered: '1610',
        imageUrl: '/images/ganymede.jpg'
      }
    }
  };

  // Check if the planet and moon exist
  if (!moonData[planetId] || !moonData[planetId][moonId]) {
    return null;
  }

  return {
    ...moonData[planetId][moonId],
    planet: planetId
  };
}

export default async function MoonPage({ params }: MoonPageParams) {
  const { planetId, moonId } = await params;
  const moon = await getMoonData(planetId, moonId);

  if (!moon) {
    notFound();
  }

  return (
    <div className="container mx-auto px-4 py-12">
      <div className="flex items-center mb-8">
        <Link
          href={`/destinations/${planetId}`}
          className="text-indigo-600 hover:underline flex items-center"
        >
          <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
          </svg>
          Back to {planetId.charAt(0).toUpperCase() + planetId.slice(1)}
        </Link>
      </div>

      <h1 className="text-4xl font-bold mb-8">{moon.name}</h1>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
        <div className="relative h-96 lg:h-auto rounded-lg overflow-hidden">
          <Image
            src={moon.imageUrl}
            alt={moon.name}
            fill
            className="object-cover"
            preload
          />
        </div>

        <div className="space-y-6">
          <p className="text-lg text-gray-700">{moon.description}</p>

          <div className="bg-gray-50 p-6 rounded-lg shadow-sm">
            <h2 className="text-2xl font-semibold mb-4">Information</h2>
            <table className="w-full">
              <tbody>
                <tr className="border-b">
                  <th className="text-left py-2">Planet</th>
                  <td className="text-right py-2">{moon.planet.charAt(0).toUpperCase() + moon.planet.slice(1)}</td>
                </tr>
                <tr className="border-b">
                  <th className="text-left py-2">Diameter</th>
                  <td className="text-right py-2">{moon.diameter}</td>
                </tr>
                <tr className="border-b">
                  <th className="text-left py-2">Orbit Distance</th>
                  <td className="text-right py-2">{moon.orbitDistance}</td>
                </tr>
                <tr>
                  <th className="text-left py-2">Discovered</th>
                  <td className="text-right py-2">{moon.discovered}</td>
                </tr>
              </tbody>
            </table>
          </div>

          <div className="flex space-x-4">
            <a
              href={`/destinations/${planetId}/${moonId}/research`}
              className="px-6 py-3 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors"
            >
              Scientific Research
            </a>
            <a
              href={`/destinations/${planetId}/${moonId}/landing-sites`}
              className="px-6 py-3 border border-indigo-600 text-indigo-600 rounded-lg hover:bg-indigo-50 transition-colors"
            >
              Landing Sites
            </a>
          </div>
        </div>
      </div>
    </div>
  );
}

export async function generateStaticParams() {
  // We generate all possible combinations of planets and their moons
  return [
    { planetId: 'mars', moonId: 'phobos' },
    { planetId: 'mars', moonId: 'deimos' },
    { planetId: 'jupiter', moonId: 'europa' },
    { planetId: 'jupiter', moonId: 'io' },
    { planetId: 'jupiter', moonId: 'ganymede' }
  ];
}

In this example:

  1. The component receives two parameters: planetId and moonId
  2. We use both parameters to fetch data about a specific moon of a specific planet
  3. We implement navigation back to the planet page
  4. We statically generate all known combinations of planets and moons

Catch-All and Optional Catch-All Parameters

In the Quantum Metropolis, some transport lines are so flexible that they can reach any number of points along the route, collecting all relevant route data as travel parameters. In Next.js 16, the equivalents are catch-all and optional catch-all segments.

Catch-All Segments ([...param])

A catch-all segment, denoted as [...param], matches a path with any number of segments. All matched segments are passed as an array.

app/
  β”œβ”€β”€ stellar-objects/
  β”‚   β”œβ”€β”€ [...path]/           # matches /stellar-objects/any/number/of/segments
  β”‚   β”‚   └── page.tsx
  β”‚   └── page.tsx              # matches /stellar-objects

Implementation of a page with a catch-all segment:

// app/stellar-objects/[...path]/page.tsx
type CatchAllParams = {
  params: Promise<{
    path: string[];
  }>;
};

export default async function StellarObjectsPage({ params }: CatchAllParams) {
  const { path } = await params;

  return (
    <div className="container mx-auto px-4 py-12">
      <h1 className="text-4xl font-bold mb-8">Stellar Objects Browser</h1>

      <div className="bg-gray-100 p-4 rounded mb-8">
        <p className="font-mono">Path: /{path.join('/')}</p>
        <p>Segments: {path.length}</p>
        <ul className="list-disc pl-6 mt-2">
          {path.map((segment, index) => (
            <li key={index}>Segment {index + 1}: {segment}</li>
          ))}
        </ul>
      </div>

      {/* Normal page content here... */}
    </div>
  );
}

Example URL: /stellar-objects/stars/main-sequence/g-type will be matched to this page, and path read with await params will be the array ["stars", "main-sequence", "g-type"].

Optional Catch-All Segments ([[...param]])

An optional catch-all segment, denoted as [[...param]] (double square brackets), works similarly to the standard catch-all, but also matches the path without any additional segments.

app/
  β”œβ”€β”€ knowledge-base/
      β”œβ”€β”€ [[...topic]]/         # matches /knowledge-base, /knowledge-base/planets, /knowledge-base/planets/terrestrial, etc.
          └── page.tsx

Implementation:

// app/knowledge-base/[[...topic]]/page.tsx
type OptionalCatchAllParams = {
  params: Promise<{
    topic?: string[];
  }>;
};

export default async function KnowledgeBasePage({ params }: OptionalCatchAllParams) {
  const { topic } = await params;

  // If topic doesn't exist, we're on the main knowledge base page
  const isRoot = !topic || topic.length === 0;

  return (
    <div className="container mx-auto px-4 py-12">
      <h1 className="text-4xl font-bold mb-8">
        {isRoot ? 'Space Knowledge Base' : 'Topic: ' + topic.join(' > ')}
      </h1>

      {isRoot ? (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          <TopicCard title="Planets" href="/knowledge-base/planets" />
          <TopicCard title="Stars" href="/knowledge-base/stars" />
          <TopicCard title="Galaxies" href="/knowledge-base/galaxies" />
          {/* More topic cards... */}
        </div>
      ) : (
        <div>
          <div className="bg-gray-100 p-4 rounded mb-8">
            <p>You are browsing topic: <strong>{topic.join(' > ')}</strong></p>

            <div className="mt-4">
              <a href="/knowledge-base" className="text-indigo-600 hover:underline">
                Return to the main knowledge base page
              </a>
            </div>
          </div>

          {/* Specific topic content... */}
        </div>
      )}
    </div>
  );
}

function TopicCard({ title, href }: { title: string; href: string }) {
  return (
    <a href={href} className="block p-6 bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow">
      <h2 className="text-xl font-semibold mb-2">{title}</h2>
      <p className="text-gray-600">Discover knowledge about {title.toLowerCase()}.</p>
    </a>
  );
}

This page will match both /knowledge-base (main knowledge base page) and /knowledge-base/planets/terrestrial (specific topic).

Parameters in Route Handlers

In the Quantum Metropolis, not only citizen transport lines use route parameters - automated systems also communicate with each other through dynamically configured channels. In Next.js 16, the equivalent is Route Handlers, which can also use dynamic segments.

Dynamic Segments in API Routes

app/
  β”œβ”€β”€ api/
      β”œβ”€β”€ planets/
          β”œβ”€β”€ [id]/
          β”‚   └── route.ts     # matches /api/planets/:id
          └── route.ts         # matches /api/planets

Implementation of a Route Handler with a dynamic segment:

// app/api/planets/[id]/route.ts
import { NextRequest, NextResponse } from 'next/server';

// Type for parameters
type PlanetRouteContext = {
  params: Promise<{
    id: string;
  }>;
};

// Sample data
const planetData: Record<string, { id: string; name: string; type: string; habitable: boolean }> = {
  'mars': {
    id: 'mars',
    name: 'Mars',
    type: 'terrestrial',
    habitable: false
  },
  'earth': {
    id: 'earth',
    name: 'Earth',
    type: 'terrestrial',
    habitable: true
  },
  'jupiter': {
    id: 'jupiter',
    name: 'Jupiter',
    type: 'gas-giant',
    habitable: false
  }
};

export async function GET(
  request: NextRequest,
  { params }: PlanetRouteContext
) {
  const { id } = await params;

  // Check if the planet exists
  if (!planetData[id]) {
    return NextResponse.json(
      { error: 'Planet not found' },
      { status: 404 }
    );
  }

  // Return planet data
  return NextResponse.json(planetData[id]);
}

export async function PUT(
  request: NextRequest,
  { params }: PlanetRouteContext
) {
  const { id } = await params;

  // Check if the planet exists
  if (!planetData[id]) {
    return NextResponse.json(
      { error: 'Planet not found' },
      { status: 404 }
    );
  }

  try {
    // Parse data from the request
    const updateData = await request.json();

    // Update planet data (simulation only)
    // In a real application, we would save this to a database
    const updatedPlanet = {
      ...planetData[id],
      ...updateData
    };

    // Return the updated data
    return NextResponse.json(updatedPlanet);
  } catch (error) {
    return NextResponse.json(
      { error: 'Invalid data' },
      { status: 400 }
    );
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: PlanetRouteContext
) {
  const { id } = await params;

  // Check if the planet exists
  if (!planetData[id]) {
    return NextResponse.json(
      { error: 'Planet not found' },
      { status: 404 }
    );
  }

  // Delete the planet (simulation only)
  // In a real application, we would delete it from the database

  return NextResponse.json({ success: true });
}

In this example:

  1. The Route Handler handles requests for a specific planet identified by id
  2. We implement GET, PUT, and DELETE methods for managing planet data
  3. The id parameter is available through the params object passed to the handler functions

Retrieving Query Parameters

In the Quantum Metropolis, beyond the main routes, the transportation system can be additionally configured through optional parameters such as "expressFlight" or "comfortLevel". In the world of Next.js, these optional settings are represented by query parameters.

Accessing Query Parameters in Server Components

// app/search/page.tsx
import { Suspense } from 'react';

// This is a server component
export default async function SearchPage({
  searchParams
}: {
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}) {
  // Get query parameters
  const query = (await searchParams).q || '';
  const category = (await searchParams).category || 'all';
  const page = Number((await searchParams).page) || 1;

  return (
    <div className="container mx-auto px-4 py-12">
      <h1 className="text-4xl font-bold mb-8">Space Search Engine</h1>

      <div className="mb-8">
        <p>Search: <strong>{query}</strong></p>
        <p>Category: <strong>{category}</strong></p>
        <p>Page: <strong>{page}</strong></p>
      </div>

      <Suspense fallback={<div>Loading results...</div>}>
        <SearchResults query={query} category={category} page={page} />
      </Suspense>
    </div>
  );
}

// This component fetches and displays results
async function SearchResults({
  query,
  category,
  page
}: {
  query: string | string[],
  category: string | string[],
  page: number
}) {
  // Normally we would fetch data based on the parameters
  // Simulating delay for Suspense demonstration
  await new Promise(resolve => setTimeout(resolve, 1000));

  // If there's no query, display a message
  if (!query) {
    return (
      <div className="bg-gray-100 p-8 rounded-lg text-center">
        <p className="text-lg">Enter a phrase to start searching.</p>
      </div>
    );
  }

  // Normally we would display search results here
  return (
    <div className="space-y-6">
      <div className="p-6 bg-white rounded-lg shadow">
        <h2 className="text-xl font-semibold mb-2">Result 1</h2>
        <p>Found for: {query}</p>
      </div>
      <div className="p-6 bg-white rounded-lg shadow">
        <h2 className="text-xl font-semibold mb-2">Result 2</h2>
        <p>Found for: {query}</p>
      </div>
      <div className="p-6 bg-white rounded-lg shadow">
        <h2 className="text-xl font-semibold mb-2">Result 3</h2>
        <p>Found for: {query}</p>
      </div>

      <div className="flex justify-center space-x-2 mt-8">
        <a
          href={`/search?q=${query}&category=${category}&page=${Math.max(1, page - 1)}`}
          className={`px-4 py-2 border rounded ${page === 1 ? 'text-gray-400 cursor-not-allowed' : 'text-indigo-600 hover:bg-indigo-50'}`}
        >
          Previous
        </a>
        <span className="px-4 py-2 bg-indigo-600 text-white rounded">
          {page}
        </span>
        <a
          href={`/search?q=${query}&category=${category}&page=${page + 1}`}
          className="px-4 py-2 border rounded text-indigo-600 hover:bg-indigo-50"
        >
          Next
        </a>
      </div>
    </div>
  );
}

In this example:

  1. The SearchPage component receives searchParams as props, containing all query parameters from the URL
  2. We use these parameters to configure the search
  3. We implement the SearchResults component, which fetches data based on the parameters
  4. We use Suspense to handle the loading state

Accessing Query Parameters in Route Handlers

// app/api/search/route.ts
import { NextRequest, NextResponse } from 'next/server';

export async function GET(request: NextRequest) {
  // Get URL from the request
  const { searchParams } = new URL(request.url);

  // Get query parameters
  const query = searchParams.get('q');
  const category = searchParams.get('category') || 'all';
  const page = Number(searchParams.get('page')) || 1;
  const limit = Number(searchParams.get('limit')) || 10;

  // Check if query exists
  if (!query) {
    return NextResponse.json(
      { error: 'The q (query) parameter is required' },
      { status: 400 }
    );
  }

  // Here we would normally fetch data from a database
  // For the sake of this example, we return simulated data
  const results = Array.from({ length: limit }, (_, i) => ({
    id: `result-${(page - 1) * limit + i + 1}`,
    title: `Result ${(page - 1) * limit + i + 1} for "${query}"`,
    category,
    relevance: Math.round(Math.random() * 100)
  }));

  return NextResponse.json({
    query,
    category,
    page,
    limit,
    totalResults: 100, // Simulated total number of results
    results
  });
}

In this example:

  1. We use new URL(request.url).searchParams to get query parameters
  2. We extract and validate specific parameters
  3. We return data appropriate for the given parameters

Generating Dynamic Metadata

In the Quantum Metropolis, every transport line has dynamically generated route information available through the city's information system. In Next.js 16, we can generate dynamic metadata for each page using the generateMetadata function.

// app/destinations/[planetId]/page.tsx
import type { Metadata } from 'next';

// Type for parameters
type PlanetParams = {
  params: Promise<{
    planetId: string;
  }>;
};

// Function generating metadata based on planetId
export async function generateMetadata(
  { params }: PlanetParams
): Promise<Metadata> {
  const { planetId } = await params;

  // Fetching planet data
  const planet = await getPlanetData(planetId);

  // If the planet doesn't exist, return default metadata
  if (!planet) {
    return {
      title: 'Planet not found | Quantum Voyages',
      description: 'No information found about the requested planet.'
    };
  }

  // Return planet-specific metadata
  return {
    title: `${planet.name} | Quantum Voyages`,
    description: planet.description.substring(0, 160), // Limit to 160 characters for SEO
    openGraph: {
      title: `Discover ${planet.name} with Quantum Voyages`,
      description: planet.description.substring(0, 160),
      images: [
        {
          url: `https://example.com${planet.imageUrl}`,
          width: 1200,
          height: 630,
          alt: planet.name
        }
      ]
    }
  };
}

// Rest of the component code...

In this example:

  1. generateMetadata receives the same params as the page component
  2. We use planetId to fetch planet data
  3. We generate dynamic metadata, including title, description, and Open Graph data
  4. These metadata are used to optimize the page's SEO

Metadata is collected from the root layout down to the page: Next.js shallowly merges the objects from the successive segments (fields defined in the page override the same fields from the layout), and the result goes into the document's <head>.

Summary

Dynamic path segments and parameters in Next.js 16 are powerful tools that enable the creation of flexible and interactive applications. Just as in the Quantum Metropolis, where the transportation system adapts to the needs of its citizens, dynamic routing in Next.js adapts to user needs.

Key points to remember:

  1. Dynamic segments are created by placing the parameter name in square brackets [param]
  2. Parameter values are available in page components through the params prop
  3. Catch-all segments ([...param]) allow matching multiple path segments
  4. Optional catch-all segments ([[...param]]) work similarly but also match the path without additional segments
  5. Query parameters are available through the searchParams prop in page components
  6. Dynamic metadata can be generated based on path parameters

With these features, you can build advanced applications with intuitive navigation and rich functionality tailored to specific user needs.

In the next chapter, we'll discover how to efficiently navigate between different pages in our application using the Link component and the useRouter hook.

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. Dynamic URL segments in App Router are created using:

  2. 2. The loading.js file in App Router is displayed:

  3. 3. The error.js file in App Router is used for:

Hands-on tasks in the game

  • Code editor

    Create the page app/product/[id]/page.js: default-export an async ProductPage({ params }) component. In Next.js 16 params is a Promise, so read id with const { id } = await params and display an h1 heading with the text β€œProduct {id}”.

  • Vertical ordering

    Arrange the generateStaticParams function syntax in App Router

  • Code editor

    Create a loading.js file with a default-exported Loading component that displays the text β€œLoading...” (you can add a spinner next to it, e.g. a div with the spinner class).

  1. QuestionDynamic URL Segments
  2. QuestionThe loading.js File in App Router
  3. Coding taskPractice: Dynamic Product Page
  4. Put in ordergenerateStaticParams Syntax
  5. QuestionThe error.js File in App Router
  6. Coding taskPractice: Loading UI

Useful articles