fruxo
fruxo

Reputation: 755

How can I get posts by year/month with nextjs and contentful?

I'm creating a blog with Next.js using Contentful CMS.

My folder structure looks like this right now pages/blog/[year]/[month]/[slug].js

The year and month folder each has its own index.js

Right now I'm working on the year part it, this is how I generated the paths for all years which contains any blog post.

export async function getStaticPaths() {
  let data = await client.getEntries({
    content_type: 'blog_post',
    select: 'sys.id,fields.publishDate',
    limit: 1000,
  })

  const allYears = data.items
    .map((item) => moment(item.fields.publishDate).format('YYYY'))
    .sort()

  // Get unique values.
  const years = [...new Set(allYears)]

  // Create paths.
  const paths = years.map((year) => {
    return {
      params: { year },
    }
  })

  return {
    paths,
    fallback: false,
  }
}

So far so good, but I have no idea how to query my contentful posts in getStaticProps? Maybe contentful doesn't support it? The only other way I would be able to do it is to filter all posts manually, but that doesn't feel like the right way to do it.

export async function getStaticProps({ params: { year } }) {
  let data = await client.getEntries({
    content_type: 'blog_post',
    // I assume I somehow have to pass my year in the query
  })

  return {
    props: {
      data,
    },
  }
}

Contentful returns date strings like this: 2021-03-03T00:00+01:00

So my question is, how could I best solve this? Has anyone encountered the same problem?

Upvotes: 2

Views: 607

Answers (1)

juliomalves
juliomalves

Reputation: 50308

You could use the range operators on the pusblishDate field to filter the results down to the given year.

export async function getStaticProps({ params: { year } }) {
    const nextYear = parseInt(year, 10) + 1 // May need to parse if `year` is a string
    let data = await client.getEntries({
        content_type: 'blog_post',
        'fields.publishDate[gte]': `${year}-01-01T00:00:00Z`,
        'fields.publishDate[lt]': `${nextYear}-01-01T00:00:00Z`
    })

    return {
        props: { data }
    }
}

Upvotes: 2

Related Questions