Having trouble with getStaticProps serialization error in Next.js?

I encountered an error in my Next.js application that reads as follows:

Error: Error serializing `.posts[0]` returned from `getStaticProps` in "/blog". Reason: `object` ("[object Promise]") cannot be serialized as JSON. Please only return JSON serializable data types.

I suspect there is a problem with resolving promises somewhere, but I'm struggling to identify it. Any assistance would be greatly appreciated!

index.js source code

export async function getStaticProps() {
    const posts = await getSortedPosts()

    return { props: { posts } }
}

posts.js source code

export async function getSortedPosts() {
    const fileNames = readdirSync(POSTS_DIR)
    const allPostsData = fileNames.map(fileName => {
        const slug = fileName.replace(/\.md$/, '')
        return getPost(slug)
    });
    await Promise.all(allPostsData);

    return allPostsData.sort((a, b) => (a.date < b.date ? 1 : -1))
}

export async function getPost(slug) {
    const fullPath = path.join(POSTS_DIR, `${slug}.md`)
    const fileContents = readFileSync(fullPath, 'utf8')

    const { content, data: meta } = parseYaml(fileContents)
    const contentHtml = await markdownToHtml(content)

    return {
        slug,
        contentHtml,
        ...meta,
    }
}

async function markdownToHtml(md) {
    const processedContent = await remark()
        .use(remarkHtml)
        .process(md)

    return processedContent.toString()
}

Answer №1

By utilizing the power of Promise.all and passing it on, I successfully managed to untangle the promise chain.

const promises = fileNames.splice(0, 2).map(fileName => {
        const slug = fileName.replace(/\.md$/, '')
        return getPost(slug)
    });
    const allPostsData = await Promise.all(promises); // Capturing result of promise chain

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

I am encountering an issue with retrieving API JSON data in NextJS where I am receiving an

Instead of receiving data in my console log, I am seeing undefined. This is my Index.js file (located in the pages folder) import Head from "next/head"; import Link from "next/link"; import axios from "axios"; import Test fro ...

Exploring the power of jQuery's deferred method and utilizing the ajax beforeSend

Using the deferred object in $.ajax allows for: Replacing the success-callback with the deferred-method done() Replacing the error-callback with the deferred-method fail() And replacing the complete-callback with always() When using: var jqxhr = $.ajax ...

How can I keep dragging objects on Raphael JS Freetransform without showing the handles?

Hey there! Currently, I am immersed in a new project that hinges on the utilization of Raphael JS alongside the Raphael.Freetransform plugin. The plugin has been performing admirably with smooth transitions so far. Nonetheless, upon utilizing the hideHandl ...

I'm looking for help on creating a three-column table using javascript/jquery. The table should display Product, Price, and Discount (which is calculated at 20%). Can anyone

Check out this code snippet. var items = ["Laptop", "Tablet", "Smartphone", "Headphones", "Camera"]; var costs = [599.99, 299.99, 799.99, 149.99, 499.99]; displayItems = ""; totalCost = 0; for (var j = 0; j < items.length; j++) { displayItems += " ...

Tips for leveraging a button to trigger server-side actions

Being a novice in web development, I'm currently working on a straightforward website that enables users to download files from the server side. These files are not pre-created; instead, there will be a button on the HTML page. When a user clicks this ...

Incorporating an external HTML page's <title> tag into a different HTML page using jQuery

I am faced with a challenge involving two files: index.html and index2.html. Both of these files reside in the same directory on a local machine, without access to PHP or other server-side languages. My goal is to extract the <title>Page Title</ ...

Leveraging Expressjs to act as a proxy for handling cross-origin requests made via AJAX

I'm working on a website that relies entirely on external APIs, without any server-side logic. All data will be retrieved from an external API. The backend server is mainly used for asset management and routing. We've decided to use nodejs with e ...

Issue with React Toggle functionality on mobile devices

I have a hamburger toggle that I found in a template, but it doesn't seem to be functioning correctly. How can I activate the on/off toggle feature? When I click the toggle, nothing happens. What am I missing? <div data-testid="header"> ...

Could you break down the concept of the for/in loop for me?

/* Follow the instructions provided to implement each function. The parameters of a function that reference `cart` pertain to an object structured like this: { "Gold Round Sunglasses": { quantity: 1, priceInCents: 1000 }, "P ...

Similar to the filter() method in Vanilla Javascript but behaves in a equivalent way to

Looking to convert some JQuery code to Vanilla JS. $('#myID :not(a, span)').contents().filter( function() { return this.nodeType === 3 && this.data.trim().length > 0;}) .wrap('<span class="mySpanClass" />'); I&a ...

Troubleshooting a Safari bug with element.click()

When the 'subButton2' button is clicked, the 'uploadBtn'(display:none;) should also be clicked. This functionality needs to work across different browsers: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_html_click The cod ...

extracting values from an array using the map function in React

In React JSX, I have an array called levels that may contain arrays with various level names such as one, two, and three. Within my render function, I utilize {renderLevels} to display all levels separated by commas. This approach works well: const rende ...

Countdown component in Ant Design failing to display correct date

I’m currently working on developing a specific date component using react in conjunction with antd. Below is the code snippet I am utilizing: import { Statistic, Col, Row } from 'antd'; const { Countdown } = Statistic; const deadline = Date.pa ...

Can you guide me on setting a background image URL for rails using javascript?

Within my Rails application, I have a collection of content paired with image buttons (each piece of content has an associated image). When a user clicks on one of these buttons, my goal is to display the corresponding image. All of my images are stored u ...

Converting a promise of type <any> to a promise of type <entity>: A beginner's guide

As a newcomer to TypeScript and NestJS, I am wondering how to convert Promise<any[]> to Promise<MyEntity[]> in order to successfully execute the following code: const usersfromTransaction = this.repoTransaction .createQueryBuilder() ...

Is it possible for PHP to use the set cookie function to replace the cookie value set by JQuery cookie?

I'm facing an issue where I want a single cookie to be set and its value updated by PHP when a user logs in. However, currently it seems to just create a new separate cookie each time. Below is the code snippet where I am trying to set the cookie valu ...

Is a referrer included in AJAX requests made from the background page of a Google Chrome Extension?

Can anyone confirm if AJAX requests sent from the background page of my Chrome Extension will include referrer information? I'm wondering about this. Appreciate any insights you can provide! ...

Switch up primary and secondary color schemes with the Material UI Theme swap

Exploring Material UI themes for React JS is a new venture for me. I am facing a scenario where I need to dynamically change the theme colors (Primary & Secondary) based on a selected type from a dropdown menu. Similar to the color customization options av ...

Updating two separate <DIV> elements with a single AJAX request

Can two different targeted DIVs be updated simultaneously using a single ajax call? Consider the index.html code snippet below: <script> xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.rea ...

I am looking for a string with this particular format in JavaScript

I am working with a JSON string array that looks like this: var dataMaster = [ {"id":1,"name":"John Doe","age":30}, {"id":2,"name":"Jane Smith","age":28} ] If you want to see how I would like to transform this data, please visit the following lin ...