3

I want to create a dynamic route structure for my next.js project, so the main directory would be countries and there will be many other countries under that directory.

www.mysite.com/countries
www.mysite.com/countries/united-states
www.mysite.com/countries/france
www.mysite.com/countries/united-kingdom
....

In my pages folder, I create a folder called countries and created a file [...slug].js. I have to create a file index.js inside the countries folder for www.mysite.com/countries to be accessible.

The issue is that index.js and [...slug].js have the same code, and I want to have only 1 file to maintain. How can I configure nextjs to use [...slug].js for www.mysite.com/countries and any sub pages under it?

1 Answer 1

3

You can simply change [...slug].js to [[...slug]].js to catch all routes starting with countries. It is treated as optional URL parameters in NextJs.
Official NextJs documentation also said that:

Catch all routes can be made optional by including the parameter in double brackets

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, that did it, I dont know how I missed it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.