I'm getting the following error in my Next.js app:
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 know there must be an issue resolving my promises somewhere, but I'm lost. Please help!
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()
}
I was able to resolve the promise chain by assigning the result of Promise.all and passing it along.
const promises = fileNames.splice(0, 2).map(fileName => {
const slug = fileName.replace(/\.md$/, '')
return getPost(slug)
});
const allPostsData = await Promise.all(promises); // Assign result of promise chain
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With