Next.js Optional Catch-all Routes

Last Updated : 15 Jul, 2026

Optional catch-all routes in Next.js provide a way to define dynamic routes that can match multiple path segments, allowing more flexibility in routing.

Steps to Implement

Optional catch-all routes extend the concept of catch-all routes by allowing you to handle routes with a variable number of segments, including the option of no segments at all.

  • We can make catch-all routes optional in Next.js using optional catch-all routes. 
  • For this, we have to add three dots inside the double square brackets in the name of the file.

For example:-

src/app/[[...slug]]/page.js

Steps to Create Next.js Application

Step 1: Create a new Next.js application using the commands below:

npx create-next-app@latest my-next-app
cd my-next-app

Project Structure:

Screenshot-2026-07-01-182849

Example: Create a folder named [[...gfg]] inside the src/app directory and add a page.js file inside it. Then add the following code.

JavaScript
// Filename - src/app/[[...gfg]]/page.js
export default async function Gfg({ params }) {
  const { gfg } = await params;
  return (
    <h1>
      Path: /{gfg ? gfg.join("/") : ""}
    </h1>
  );
}

Here, the params object contains all matched route segments. If the URL contains multiple segments, they are available as an array and are displayed as the current path.

Step to Run Application: Run the application using the following command from the root directory of the project.

npm run dev

Output:

Difference Between Catch-all Routes and Optional Catch-all Routes

  • In optional catch-all routes, the route without any additional path segments also matches. For example, if the route is [[...gfg]], both /route and /route/ads will match.
  • In catch-all routes ([...gfg]), the base route (/route) will not match, and at least one path segment is required.

Now rename the [[...gfg]] folder to [...gfg] and keep the same page.js file inside it.

JavaScript
// Filename - src/app/[...gfg]/page.js
export default async function Gfg({ params }) {
  const { gfg } = await params;

  return (
    <h1>
      Path: /{gfg.join("/")}
    </h1>
  );
}

Now this will not match the path '/route'.

Step to Run Application: Run the application using the following command from the root directory of the project.

npm run dev

Output:

Comment

Explore