1

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 '/'.
1
  • In which file is getStaticPaths ? Commented Apr 29, 2021 at 7:13

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.