Search code examples
reactjsnext.jsssg

How to generate index.html with getStaticPaths in Next.js?


I am trying to generate an index.html page with getStaticPaths in Next.JS but every time I try to do so it throws out an error or creates an index directory instead of a file.

So far I have tried passing: '', '/' and 'index' in params.page. I also tried adding trailingSlash: true, in the next.config file but this didn't work either.

I have a [page].js file in the pages directory. With this file, I generate numerous pages since the [page].js file is a templating file. I use this templating method because there are a lot of common components and the only thing that differs on each page is the "main content". Imagine the following, generating 10 pages where each one of them has the same navbar and side menu but the content (text) is different. And so I try to generate 10 pages while one of them is the index.html one but instead of generating a .html file it generates an index directory. How can I fix that is my question?

export const getStaticPaths = async () => {
    return {
        paths: [{
            params: { // Imagine the following code for another 9 pages
                page: 'index' // Only the `index` one has a problem (creates a directory instead of file)
            }
        }]
    };
}

If I pass any other string apart from index in params.page it would create a [my_string].html page. I want to be able to create an index.html page with next.js' getStaticPaths method.


Solution

  • Might be a bit late for an answer but NextJS has added an OPTIONAL catch all routes.

    You can now name your page using two brackets [[...slug]].

    On get Static Props params will be an empty object and won't have a slug property, so you can do this check:

    
    export const getStaticProps: GetStaticProps<{ data: PageData }> = async ({ params }) => {
      const homePage = !!!params.url;
    
      // now do your logic if the page is the home.
     
    
    

    Please check my question here:

    https://github.com/vercel/next.js/discussions/34311#discussioncomment-2178744