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()
}