Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 36 ยท Markdown and MDX Sites

Markdown Blog Pages with gatsby-transformer-remark

Turn Markdown files into blog pages: source them from disk, parse front matter and HTML with remark, create slugs in onCreateNode and pages in createPages.

Markdown is the natural format for blog posts and documentation: it is plain text, lives in Git, and has no database. Gatsby can read a folder of .md files, turn them into data, and create one page per file. This lesson walks through the classic pipeline, which uses gatsby-transformer-remark. The same shape (source, transform, slug, template) appears again for MDX in the next lesson.

The pipeline

flowchart LR
  A["content/posts/*.md"] --> B["gatsby-source-filesystem: File nodes"]
  B --> C["transformer-remark: MarkdownRemark nodes"]
  C --> D["onCreateNode: add slug field"]
  D --> E["createPages: one page per node"]
  E --> F["blog-post template renders html"]

Each stage adds to the data layer; the template only reads the result.

Configuration

JavaScript
// gatsby-config.js (real Gatsby, read-only)
module.exports = {
  siteMetadata: { title: "My Blog", siteUrl: "https://example.com" },
  plugins: [
    { resolve: "gatsby-source-filesystem", options: { name: "posts", path: `${__dirname}/content/posts` } },
    {
      resolve: "gatsby-transformer-remark",
      options: {
        plugins: [
          "gatsby-remark-prismjs",
          { resolve: "gatsby-remark-images", options: { maxWidth: 800 } },
          "gatsby-remark-autolink-headers",
        ],
      },
    },
  ],
}

A post looks like this. The block between the --- lines is front matter, in YAML:

MD
---
title: "Hello Gatsby"
date: 2025-03-14
tags: [gatsby, markdown]
description: "My first post."
---

Welcome! This is the **body** of the post.

Gatsby creates a MarkdownRemark node per file with frontmatter { title date tags }, html (the rendered body), excerpt, timeToRead, headings and tableOfContents. You can inspect all fields in the GraphiQL explorer at localhost:8000/___graphql while running gatsby develop.

Step 1: add a slug in onCreateNode

Nodes have no URL yet. onCreateNode runs for every node, so we compute a slug from the file path and attach it as a field. createFilePath from gatsby-source-filesystem does the path work.

JavaScript
// gatsby-node.js (real Gatsby, read-only)
const { createFilePath } = require("gatsby-source-filesystem")

exports.onCreateNode = ({ node, getNode, actions }) => {
  if (node.internal.type === "MarkdownRemark") {
    const slug = createFilePath({ node, getNode, basePath: "content/posts" })
    actions.createNodeField({ node, name: "slug", value: `/blog${slug}` })
  }
}

A file content/posts/hello-gatsby.md becomes /blog/hello-gatsby/.

Step 2: createPages

JavaScript
// gatsby-node.js (real Gatsby, read-only)
const path = require("path")

exports.createPages = async ({ graphql, actions, reporter }) => {
  const result = await graphql(`
    {
      allMarkdownRemark(sort: { frontmatter: { date: DESC } }) {
        nodes { id fields { slug } }
      }
    }
  `)
  if (result.errors) {
    reporter.panicOnBuild("Could not load posts", result.errors)
    return
  }
  const posts = result.data.allMarkdownRemark.nodes
  posts.forEach((post, i) => {
    actions.createPage({
      path: post.fields.slug,
      component: path.resolve("src/templates/blog-post.js"),
      context: {
        id: post.id,
        previousId: i === 0 ? null : posts[i - 1].id,
        nextId: i === posts.length - 1 ? null : posts[i + 1].id,
      },
    })
  })
}

The context object becomes GraphQL variables in the template's page query, which is how one template shows different posts.

Step 3: the template

JSX
// src/templates/blog-post.js (real Gatsby, read-only)
import * as React from "react"
import { graphql } from "gatsby"

export default function BlogPost({ data }) {
  const post = data.markdownRemark
  return (
    <article>
      <h1>{post.frontmatter.title}</h1>
      <p>{post.frontmatter.date} ยท {post.timeToRead} min read</p>
      <div dangerouslySetInnerHTML={{ __html: post.html }} />
    </article>
  )
}

export const query = graphql`
  query ($id: String!) {
    markdownRemark(id: { eq: $id }) {
      html
      timeToRead
      frontmatter { title date(formatString: "MMMM D, YYYY") }
    }
  }
`

dangerouslySetInnerHTML is acceptable here because the HTML is produced at build time from your own files. Never use it with user-submitted content.

Try the pipeline

Gatsby cannot run here, so these stand-ins show the logic with plain JavaScript. First: parse front matter, make a slug and compute reading time.

JS Stand-in: front matter, slug and reading time

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Second: a tiny Markdown-to-HTML converter and a createPages imitation that returns the pages with previous/next ids.

JS Stand-in: createPages with previous and next

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common mistakes

  • Querying fields { slug } before adding it in onCreateNode: you get a "Cannot query field" error.
  • Using createFilePath with the wrong basePath, which leaves a long prefix in the URL.
  • Forgetting context ids, so every page renders the same post.
  • Putting Markdown outside the folder registered in gatsby-source-filesystem.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where do you add a slug field to Markdown nodes?

    onCreateNode runs per node, so it can compute a value and attach it as a field.
  2. 2. What does the context object in createPage do?

    Context values are available as GraphQL variables, so one template can fetch different data per page.
  3. 3. Which plugin turns Markdown File nodes into MarkdownRemark nodes?

    The source plugin reads files; the remark transformer parses them.
  4. 4. Why is dangerouslySetInnerHTML okay for post.html?

    You control the content; it would be unsafe with user-supplied HTML.

Summary

  • Source plugin reads files, remark transformer parses them, onCreateNode adds slugs, createPages creates pages.
  • Front matter becomes frontmatter fields; the body becomes html.
  • context passes ids to the template's query; compute previous and next there too.
  • Use remark sub-plugins for code highlighting and images.

Next: MDX in Gatsby