Use optional catch-all routes with getStaticPaths
See original GitHub issueBug report
Describe the bug
I’m trying to build dynamic nested SSG routes with Next. The goal is to be able to create any page using an external data source. I also want this method to cover the root (path /
) page, so I’m using optional catch-all routes.
So after enabling experimental optional catch all routes in next.config.js, here is what I wrote:
In pages/[[...slug]].js
:
const MyPage = ({ slug }) => {
return <div>My page, slug {JSON.stringify(slug)}</div>;
};
export async function getStaticPaths() {
const paths = [
{
params: { slug: [] },
},
{
params: { slug: ["home"] },
},
{
params: { slug: ["home", "page"] },
},
];
return { paths, fallback: false };
}
export async function getStaticProps({ params }) {
// Make sure params are what we expected
console.log(params);
return {
props: {
slug: params.slug,
},
};
}
export default MyPage;
When I try to access my routes (/
, home
and /home/page
), I get a 404 instead. After running yarn build
, I found out Next did this instead:
Page Size First Load JS
┌ /_app 3.47 kB 61.1 kB
├ ● /[[...slug]] 319 B 61.5 kB
├ ├ /[]
├ ├ /[home]
├ └ /[home/page]
└ ○ /404 3.25 kB 64.4 kB
And in my logs, the values of params
were:
{ slug: [ '[home', 'page]' ] }
{ slug: [ '[]' ] }
{ slug: [ '[home]' ] }
To Reproduce
Steps to reproduce the behavior, please provide code snippets or a repository:
- Create a default Next app
- Create a
next.config.js
file with this content:
module.exports = {
experimental: {
optionalCatchAll: true,
},
};
- In the pages folder, delete
index.js
and create a file called[[...slug]].js
instead - In that file, paste the code I included above
- Run
yarn build
- See the result
Expected behavior
Next.js should have created these pages instead:
Page Size First Load JS
┌ /_app 3.47 kB 61.1 kB
├ ● /[[...slug]] 319 B 61.5 kB
├ ├ /
├ ├ /home
├ └ /home/page
└ ○ /404 3.25 kB 64.4 kB
And I think the values of params
in getStaticProps should have been:
{ slug: [ 'home', 'page' ] }
{ slug: [ ] }
{ slug: [ 'home' ] }
System information
-
OS: macOS 10.15.5
-
Version of Next.js: 9.4.4
-
Version of Node.js: 12.18.2
Additional context
My code fine with regular catch-all routes, with a file called [...slug].js
and without the root page.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:4
- Comments:8 (8 by maintainers)
Top GitHub Comments
So TLDR:
ctx.params
is an empty objectThanks for the help!
This is the expected behavior. You’ll need to set a default value!
All falsy values passed into
getStaticPaths
result in the omission of the variable fromparams
.Or: