Strapi - Build a Blog Using Strapi and Next.js

This does not work if you have more than 25 articles, as the default api response is capped at 24 per api response. This should be updated to do the filter differently I believe.

Here is what I did to help this issue

  1. Use pagination to get a full list of article slugs using pagination instead of the generic /articles route that only returned 24. We have over 200 articles and this worked fine. im sure you could make it more efficient.
// fetch all articles from strapi using pagination, for each
export async function fetchStrapiArticles() {
  const articles = []
  const totalPagesMeta = await fetch(
    `${process.env.NEXT_PUBLIC_STRAPI_API_URL}/api/articles`
  ).then((res) => res.json())
  const totalPages = totalPagesMeta.meta.pagination.pageCount
  for (let i = 1; i <= totalPages; i++) {
    const articlesRes = await fetch(
      `${process.env.NEXT_PUBLIC_STRAPI_API_URL}/api/articles?pagination[page]=${i}`,
      {
        fields: ['slug']
      }
    )
    const json = await articlesRes.json()
    articles.push(...json.data)
  }

  return articles
}

  1. Call this helper method instead to generate all the slugs needed
export async function getStaticPaths() {
  const articleRes = await fetchStrapiArticles()
  const paths = articleRes.map((article) => ({
    params: { slug: article.attributes.slug }
  }))

  return { paths, fallback: false }
}

export async function getStaticProps({ params }) {
  const articlesRes = await fetchStrapi('/articles', {
    populate: ['image', 'author', 'author.image', 'keywords'],
    filters: {
      slug: params.slug
    }
  })

  const categoriesRes = await fetchStrapi('/categories')

  return {
    props: {
      article: articlesRes.data[0],
      categories: categoriesRes
    }
  }
}

1 Like