šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Multiple URL parameters in NextJs with catch-all segments: the […name] and [[…name]] folders

Learn how to use multiple URL parameters/segments in NextJs paths, with the catch-all segments; the [...name] and [[...name]] folders naming patterns.

There are a few reserved filenames and conventions that the NextJs app folder has.

For example, if we want to have dynamic URL parameters (or dynamic segments) we can use the square bracket notation. So, the below folder structure:

/app
    /blog
        /[url]
            page.js

Will give us access to URLs such as:

/blog/one
/blog/two
/blog/three

But, what if we want to have a variable number of URL parameters? Something as:

/blog/one
/blog/one/two
/blog/one/two/three ....

For cases like this, we will use catch-all segments.

Catch-all Segments folders in NextJs; the [...name] folders

In order to declare a NextJs catch-all segments folder we will need to wrap the folder name in square brackets and prefix it with the spread operator:

[...folderNameHere]

Therefore if we change the above folder structure to:

/app
    /blog
        /[...url]
            page.js

We will be able to use any number of URL parameters:

/* all of these urls will be mapped to:
/app/blog/[...url]/page.js */
/blog/one
/blog/one/two
/blog/any/numberOf/params/here

If we want to display these parameters we can use the object destructuring and retrieve them from the params object received by our blog page:

export default function Page({params}) {
    const {url = []} = params
    return <>
        <h1>Received URL params: </h1>
        <ul>
            {url.map( (p, i) => <li key={i}>{p}</li>)}
        </ul>
    </>
}

Optional Catch-all Dynamic Segments folders in NextJs; the [[...name]] folders

With the basic catch-all segments folders, we will only intercept URLs as:

/blog/one
/blog/one/two
/blog/one/two/three

However, if we access the root /blog path we will get the 404 page:
Nextjs not found page

If we want to intercept also the root path we will need to add double square brackets to the folder name:

/app
    /blog
        /[[...url]]
            page.js

Now our page.js file will intercept all the following URL formats:

/* all of these urls will be mapped to:
/app/blog/[[...url]]/page.js */
/blog
/blog/one
/blog/one/two
/blog/any/numberOf/params/here

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *