Reputation: 6239
I've building a static next.js site and want to generate a set of static pages from a folder of markdown docs (but for the purpose of this question could be any thing - text files etc). Imagine I have this docs folder:
/docs/foo/bar.md
/docs/foo/baz.md
/docs/bar/foo.md
...
/docs/foobar.md
The only way I can discover the full URL slugs is at build time where I can recurse the docs folders and discover these paths:
/docs/foo/bar
/docs/foo/baz
/docs/bar/foo
...
/docs/foobar
Normally, if I knew about the diff sub-routes I could add files like this:
pages/docs/foo/[page].js
pages/docs/bar/[page].js
...however I don't know about these sub-folders at code time to be able to do this, only at build time when I recurse the docs.
The nearest thing I can find would be a catch-all route like this:
pages/docs/[...slug].js
I know that I could easily link to a route such as /docs/foo/bar
in the app and I know that I could get the slug in the page itself like in this example, but I'm not sure if/how can I generate the static paths I need in this file using getStaticPaths
and getStaticProps
?
Any help greatly appreciated!
Upvotes: 2
Views: 612
Reputation: 6239
I managed to solve this one just now which wasn't immediately obvious to me...
In getStaticPaths
, due to the [...slug].js
, next.js expects the provided slug to be an array for the path parts, so building an array of arrays solves it:
export async function getStaticPaths() {
// Load the docs from the file system and convert their relative docs paths to arrays
const docs = [["foo", "bar"], ["foo", "baz"], ["bar", "foo"], ["foobar"]];
return {
paths: docs.map((doc) => {
return {
params: {
slug: doc,
},
};
}),
fallback: false,
};
}
...then getStaticProps
will be called per array above and I can retrieve the markdown and prepare the content as props for the page component.
Upvotes: 2