Dynamic Routes

Render Markdown

To render markdown content, we’ll use the remark library. First, let’s install it:

npm install remark remark-html

Import them in lib/posts.js:

import remark from 'remark'
import html from 'remark-html'

And update getPostData() as follows to use remark:

export async function getPostData(id) {
  const fullPath = path.join(postsDirectory, `${id}.md`)
  const fileContents = fs.readFileSync(fullPath, 'utf8')

  // Use gray-matter to parse the post metadata section
  const matterResult = matter(fileContents)

  // Use remark to convert markdown into HTML string
  const processedContent = await remark()
  const contentHtml = processedContent.toString()

  // Combine the data with the id and contentHtml
  return {

Important: We added the async keyword to getPostData because we need to use await for remark. async/await allow you to fetch data asynchronously.

That means we need to update getStaticProps in pages/posts/[id].js to use await when calling getPostData:

export async function getStaticProps({ params }) {
  // Add the "await" keyword like this:
  const postData = await getPostData(params.id)
  // ...

Finally, update the Post component to render contentHtml using dangerouslySetInnerHTML:

export default function Post({ postData }) {
  return (
      <br />
      <br />
      <br />
      <div dangerouslySetInnerHTML={{ __html: postData.contentHtml }} />

Try visiting these pages again:

You should now see the blog content:

We’re almost done! Let’s polish each page next.