Frontend
Intermediate
Josué Hernández

Josué Hernández

    Basic Dynamic Routes
    Example:
    Catch-All and Optional Parameters
    Catch-All Parameters
    Optional Catch-All Parameters
    Enhancing Routes with TypeScript
    Defining Parameter Types
    Multiple Parameters
    Using Search Parameters (searchParams)
    Example:
    Combining Parameters and Search Queries
    Example URLs:
    Output:
    Tips for Managing Dynamic Routes
    What’s New in Next.js 15 Routing?
    Why This Change Matters?
    Example: Fetching Data with Async Params
    Key Takeaways
    Conclusion
    Additional Resources

Dynamic routing is one of the core features of Next.js, enabling developers to create flexible, scalable, and modern web applications. With Next.js 15, improvements in TypeScript integration and enhanced route handling make it easier than ever to work with dynamic routes. This guide will cover everything from basic dynamic routes to advanced techniques like optional parameters and TypeScript usage.


Basic Dynamic Routes

In Next.js, you can create dynamic routes by using square brackets ([]) in file or folder names within the app directory.

Example:

File structure:

PLAIN TEXT
app/blog/[slug]/page.tsx

Accessing the route:

PLAIN TEXT
URL: /blog/my-first-post
Params: { slug: 'my-first-post' }

This captures the dynamic segment slug and makes it available as a parameter.


Catch-All and Optional Parameters

Catch-All Parameters

Catch-all routes capture multiple dynamic segments in a single parameter using [...param].

File structure:

PLAIN TEXT
app/shop/[...slug]/page.tsx

Examples:

  • /shop/a{ slug: ['a'] }
  • /shop/a/b{ slug: ['a', 'b'] }
  • /shop/a/b/c{ slug: ['a', 'b', 'c'] }

Optional Catch-All Parameters

Optional catch-all parameters are created using [[...param]], allowing the route to match with or without parameters.

File structure:

PLAIN TEXT
app/shop/[[...slug]]/page.tsx

Examples:

  • /shop{}
  • /shop/a{ slug: ['a'] }
  • /shop/a/b{ slug: ['a', 'b'] }

Optional parameters make it easier to handle routes like /shop and /shop/a within the same file.


Enhancing Routes with TypeScript

TypeScript allows you to define and enforce parameter types for better type safety and maintainability.

Defining Parameter Types

Single Dynamic Parameter:

TYPESCRIPT
// app/blog/[slug]/page.tsx

interface BlogParams {
  slug: string;
}

Catch-All Parameters:

TYPESCRIPT
// app/shop/[...slug]/page.tsx

interface ShopParams {
  slug: string[];
}

Optional Catch-All Parameters:

TYPESCRIPT
// app/shop/[[...slug]]/page.tsx

interface OptionalShopParams {
  slug?: string[];
}

Multiple Parameters

When a route contains multiple dynamic segments, define an interface for all parameters:

File structure:

PLAIN TEXT
app/[categoryId]/[itemId]/page.tsx

TypeScript:

TYPESCRIPT
interface Params {
  categoryId: string;
  itemId: string;
}

Using Search Parameters (searchParams)

Next.js 15 handles query strings (search parameters) seamlessly in page.tsx.

Example:

URL:

PLAIN TEXT
/shop?a=1&b=2

Captured searchParams:

TYPESCRIPT
{ a: '1', b: '2' }

Duplicate query parameters:

PLAIN TEXT
/shop?a=1&a=2

Captured searchParams:

TYPESCRIPT
{ a: ['1', '2'] }

You can access searchParams in page.tsx to customize page rendering based on the query string.


Combining Parameters and Search Queries

Here’s a complete example that demonstrates dynamic routing with parameters and search queries:

TYPESCRIPT
interface CategoryProps {
  params: { categories: string[] };
  searchParams: { id: string };
}

export default function Category({ params, searchParams }: CategoryProps) {
  const { categories } = params;
  const { id } = searchParams;

  return (
    <>
      <h2>Category: {categories.join(', ')}</h2>
      <p>ID: {id}</p>
    </>
  );
}

Example URLs:

  • /category/electronics?id=123
  • /category/electronics/computers?id=456

Output:

For /category/electronics/computers?id=456:

PLAIN TEXT
Category: electronics, computers
ID: 456

This demonstrates how to handle both dynamic segments (params) and query strings (searchParams) in a clean and efficient way.


Tips for Managing Dynamic Routes

  1. Keep URLs Readable: Use descriptive names for your route parameters to improve clarity.
  2. Use Catch-All Routes Sparingly: Only use [...slug] or [[...slug]] when necessary to avoid overly complex route logic.
  3. Leverage TypeScript: Define parameter types explicitly for better developer experience and fewer runtime errors.
  4. Test Edge Cases: Ensure your app handles edge cases, like missing optional parameters or invalid search queries, gracefully.

What’s New in Next.js 15 Routing?

Next.js 15 introduces a significant change in how route parameters (params and searchParams) are handled. Unlike previous versions, where parameters were directly passed as plain objects, in Next.js 15, they are now wrapped in a Promise and must be resolved using await before use.

Why This Change Matters?

  1. Better Support for Asynchronous Data Fetching
  2. Optimized Server Rendering
  3. Improved Consistency with Dynamic Rendering
  4. Enhanced Parameter Validation

Example: Fetching Data with Async Params

In Next.js 15, route parameters must be awaited before use:

TYPESCRIPT
interface ProductProps {
  params: Promise<{ productId: string }>;
}

export default async function ProductPage({ params }: ProductProps) {
  const { productId } = await params;
  const product = await fetchProductFromDB(productId);

  return <h1>Product: {product.name}</h1>;
}

This allows dynamic pages to seamlessly integrate with asynchronous data sources, improving both performance and developer experience.


Key Takeaways

  • Improved handling of asynchronous parameters for better data-fetching workflows.
  • Faster server rendering by resolving params in parallel.
  • More predictable and flexible routing behavior in line with modern React patterns.

This enhancement in Next.js 15 makes dynamic routes even more powerful, flexible, and optimized for real-world applications.


Conclusion

Dynamic routing in Next.js 15 provides powerful tools to create flexible and scalable applications. This blog introduced the basics of dynamic and optional routes, TypeScript usage, and handling search parameters.

This is just the beginning—future posts will dive deeper into advanced routing strategies and complex examples to help you unlock the full potential of Next.js dynamic routes.


Additional Resources


Josué Hernández
Josué Hernández

Last Update on 2025-01-30

Related Blogs

© 2024 Effort Stack. All rights reserved