Entre Accolades
Entre Accolades

Reputation: 11

Error 'getStaticPaths can only be used with dynamic pages, not '/'' with Next JS

I want to use getStaticPaths for my posts blog with dynamic routes but I get an error while building.

My folder with dynamic routes :

pages/articles/[category]/[slug].js

My Link Navigation:

    <Link href={`/article/${category}/${slug}`} passHref>
      <Card>
        ...some data
      </Card>
    <Link />

My getStaticPaths:

export async function getStaticPaths () {
   
  // retrieve data from cms

  const data = await getAllPreviewPosts()

  // generate the paths

  const paths = data.map( ({ fields: { slug , stackName } }) => ({ 
   params: { category: stackName, slug: slug } 
   }))

  return {
     paths, 
     fallback: false
  }   
}

export async function getStaticProps () {
 /* ... get data from cms */
}

But when I run npm run build I get this error:

Error: getStaticPaths can only be used with dynamic pages, not '/'.

Upvotes: 1

Views: 6524

Answers (2)

flexiness
flexiness

Reputation: 51

It seems the url for getStaticPaths has changed somewhat. Your folder with dynamic routes should be perhaps:

pages/articles/[category]/[[slug]].js

and not:

pages/articles/[category]/[slug].js

The difference between Catch all routes and Optional catch all routes is explained here

Given a file structure such as :

pages
│   ├── 404.js
│   ├── 500.js
│   ├── _app.js
│   └── store
│       └── [[...slug]].js

The following getStaticPaths fnct should cover all these routes:

/store
/store/portfolio
/store/design-system
/store/cart

export async function getStaticPaths() {
  return {
    paths: [
      { params: { slug: [''] } }, // <-- Get the data on the page itself
      { params: { slug: ['portfolio'] } },
      { params: { slug: ['design-system'] } },
      { params: { slug: ['cart'] } },
    ],
    fallback: false
  }
}

Upvotes: 2

arkuuu
arkuuu

Reputation: 649

getStaticPaths defines which pages next.js has to render when exporting. It is used to generate all available dynamic routes. You cannot use that data on the page itself.

To get all available categories and slugs to use it in your navigation component, you need to use getStaticProps to load the data on the page and pass it into your navigation component as props.

You can find an example for this here: https://github.com/vercel/next.js/blob/master/examples/with-static-export/pages/index.js

Upvotes: 3

Related Questions