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?
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