Is there a way to retrieve posts by year and month using nextjs and contentful?

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?

Answer №1

Utilize the range operators on the pusblishDate field to narrow down the results by a specific year.

async function fetchBlogPosts({ params: { year } }) {
    const nextYear = parseInt(year, 10) + 1 // Make sure to convert 'year' to an integer if it's 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 }
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The error message "Property 'push' of undefined in AngularJS" occurs when the push method is being called

I'm currently working on developing a basic phonebook web application to enhance my knowledge of Angular, but I've encountered an issue with this error message - "Cannot read property 'push' of undefined". Can anyone help me identify th ...

Leveraging the power of ES6 syntax in Node scripts with Babel

My npm CLI tool utilizes ES6 syntax from BabelJS, specifically arrow functions. Within the entry point of my tool, I'm using the following require: require('babel-core/register'); var program = require('./modules/program.js'); I ...

Enhance the appearance of the navbar on mobile devices by customizing the styling in Bootstrap 5

Hi everyone, this is my first time posting a question here so please be gentle :) I recently implemented a script to change the CSS of my navbar when scrolling. window.addEventListener("scroll", function () { let header = document.querySelector(".navbar") ...

What could be causing the issue with lodash throttle not functioning correctly in the useWindowSize custom hook?

I'm attempting to implement a resize event with throttle, but I'm encountering an issue. To troubleshoot, I have tried the following: import {throttle} from 'lodash' export function useWindowSize() { const [windowSize, setWindowSize] ...

Error: Improper hook call detected with no hooks being used (material-ui v5)

I've created the following basic application: import Grid from '@material-ui/core/Grid'; function App() { return ( <div className="App"> <Grid container spacing={2}> <Grid item xs={8}> ...

Customizing font color upon hover in Next.js and Tailwind.css

Recently, I developed a Navbar component that displays a purple link when navigating to pages like Home or Projects. The issue arises when the background color is light; in this case, the link turns green on hover instead of staying purple. How would I adj ...

Utilizing Google's ReCaptcha v3 with Next.js

Trying to integrate react-google-recaptcha-v3 into my React application using version 16.13.1 & Next version 9.4.4. Encountering an issue at const result = await executeRecaptcha("homepage") in pages/index.js. console.log(process.env.GOOGLE ...

Pass a byte array from the back-end code to an AJAX request

I have a web method where I am converting HTML to PDF and saving it to a local folder. The goal is for the user to download the file without needing to reload the page. To achieve this, I am attempting to make an AJAX POST call to the web method to retriev ...

Having trouble getting the AJAX script to change the background in Internet Explorer?

I'm currently experiencing an issue with an ajax script. Here is the code I am using: <script type="text/javascript"> $(document).ready(function() { $('#savecolor').click(function(){ var myVar = 'data= ...

Restricting the frequency at which a specific key value is allowed to appear in JSON documents

Within my JSON file, there is an array structured like this: { "commands": [ { "user": "Rusty", "user_id": "83738373", "command_name": "TestCommand", "command_reply": "TestReply" } ] } I have a requirement to restrict the num ...

Generate arrays with custom names by parsing JSON data

Currently, I am retrieving data from a MySQL database and converting it to JSON before passing it to a JavaScript class for chart display purposes. The challenge lies in creating arrays required by the chart from the JSON object without manually creating a ...

The Next.js build encountered an error - unable to locate function in next/script module

While constructing a CMS using next.js, one of the key components is media management through Cloudinary. The integration of the Cloudinary Media Library widget was successful during development using next/script. However, an error has now emerged that pre ...

NextAuth: Having difficulty redirecting to the page for New User registration

I can't seem to understand why the redirection to the NewUser page isn't working when a user Signs In with the CredentialsProvider. The authorize function clearly returns the "isNewUser" flag as true for new users. Take a look at the configurati ...

Creating a custom JavaScript clock based on stored database values

I am looking to create an analog clock using JavaScript. I have both working hours and off hours stored in a database. My goal is to display working hours in one color and off hours in another color on the clock. How can I achieve this? The database prov ...

Renew Firebase Token

Currently, my email and password authentication flow in web Firebase JavaScript involves generating a token that I then verify on my node.js backend using firebase-admin. To make things easier, I store this generated token in the browser's local/sessi ...

I am searching for a tool in ThreeJS that functions similar to AxisHelper, possibly a Helper class or utility

While working with Three.js, I have come across many helpful Helper classes that greatly simplify displaying and modifying the scene. However, there is one particular tool that I am struggling to find again. It is similar to the AxisHelper, but it includes ...

Comparison between using jQuery to append and execute a <script> tag versus using vanilla JavaScript

As I enhance my application, I've made the decision to embrace Bootstrap 5, which no longer relies on jQuery. Consequently, I am working to eliminate this dependency from my application entirely. One of the changes I'm making is rewriting the Ja ...

Disabling specific time slots in the mat select functionality

I have a scenario where I need to display time slots at 30-minute intervals using Mat Select. export const TIME=["12:00 AM","12:30 AM","01:00 AM","01:30 AM","02:00 AM","02:30 AM","03:00 AM&qu ...

Obtain the key by using the JSON value

I am seeking to identify the recursive keys within a JSON Object. For instance, consider the following JSON Object: { "Division1" : { "checked": true, "level": 1, "District1-1": { "checked": true, "level ...

Using a Vue component to send a form for submitting data into the backend database of a Django application

Where should the connection between a form within a Vue component and a Django backend be established? In my frontend, I am utilizing VueJS where my primary component can retrieve data from a JSON file through an API specified in my Django view and URL fi ...