Currently, I am in the process of setting up a blog using Next.js and Contentful CMS. The structure of my folders is set as follows: pages/blog/[year]/[month]/[slug].js
Each year and month folder contains its own index.js file.
Currently, my focus is on the year section, where I am generating paths for all years that have any blog posts.
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,
}
}
Everything seems to be going smoothly so far, but I'm facing a roadblock when it comes to querying my Contentful posts in getStaticProps. Is there a way to achieve this with Contentful or do I need to manually filter all posts, which doesn't seem like the ideal solution?
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 in the format: 2021-03-03T00:00+01:00. How can I best approach solving this challenge? Has anyone else encountered a similar issue?