Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 36 ยท GraphQL Data Layer

Creating Pages Programmatically

Generate Gatsby pages from data with createPages, onCreateNode slugs, page templates, context variables, pagination and tag pages, with runnable stand-ins.

File names work for pages you write by hand. A blog with 300 posts needs 300 pages, and you want to add a post by adding a Markdown file, not by editing code. Gatsby solves this with the createPages API: in gatsby-node.js you query your data, loop over the results and call createPage once per page, pointing each one at a template component. This lesson walks through the full recipe: add a slug to each node, create pages, use the context in a template, then add pagination and tag pages.

All Gatsby code is read-only. The stand-ins reproduce the same flow with plain objects, so you can see what is created.

Step 1: give every node a slug

Markdown files do not have URLs. Add a slug field in the onCreateNode API, which runs once for every node:

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

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

createFilePath builds a path from the file location (content/posts/espresso.md becomes /espresso/). The slug is stored under fields, so you query it as fields { slug }. You could also use a frontmatter value or a CMS field.

Step 2: create the pages

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

exports.createPages = async ({ graphql, actions, reporter }) => {
  const { createPage } = actions
  const postTemplate = path.resolve("./src/templates/post.js")

  const result = await graphql(`
    {
      allMarkdownRemark(sort: { frontmatter: { date: ASC } }) {
        nodes {
          id
          fields { slug }
        }
      }
    }
  `)

  if (result.errors) {
    reporter.panicOnBuild("Could not query posts", result.errors)
    return
  }

  const posts = result.data.allMarkdownRemark.nodes
  posts.forEach((post, index) => {
    createPage({
      path: post.fields.slug,
      component: postTemplate,
      context: {
        id: post.id,
        previousId: index === 0 ? null : posts[index - 1].id,
        nextId: index === posts.length - 1 ? null : posts[index + 1].id,
      },
    })
  })
}

createPage needs three things: a path, a component (an absolute path to the template) and a context. Keep context small: IDs and flags, not whole objects. The template then queries what it needs using the IDs (page queries).

flowchart TD
  A["onCreateNode<br/>adds fields.slug"] --> B["createPages<br/>queries all posts"]
  B --> C["createPage x N<br/>path + component + context"]
  C --> D["Template runs its page query<br/>with context variables"]
  D --> E["HTML file per post"]

Data flows from nodes, to slugs, to pages, to templates.

Step 3: the template

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

const PostTemplate = ({ data }) => {
  const { post, previous, next } = data
  return (
    <article>
      <h1>{post.frontmatter.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: post.html }} />
      <nav>
        {previous && <Link to={previous.fields.slug}>Previous: {previous.frontmatter.title}</Link>}
        {next && <Link to={next.fields.slug}>Next: {next.frontmatter.title}</Link>}
      </nav>
    </article>
  )
}

export const query = graphql`
  query ($id: String!, $previousId: String, $nextId: String) {
    post: markdownRemark(id: { eq: $id }) {
      html
      frontmatter { title }
    }
    previous: markdownRemark(id: { eq: $previousId }) {
      fields { slug }
      frontmatter { title }
    }
    next: markdownRemark(id: { eq: $nextId }) {
      fields { slug }
      frontmatter { title }
    }
  }
`

export default PostTemplate

Variables declared without ! can be null, so the first and last posts simply return null for previous or next. The dangerouslySetInnerHTML is acceptable here because the HTML comes from your own Markdown, not from users.

Pagination and tag pages

The same mechanism creates any list pages. For a paginated blog index:

JavaScript
const postsPerPage = 10
const pageCount = Math.ceil(posts.length / postsPerPage)

Array.from({ length: pageCount }).forEach((_, i) => {
  createPage({
    path: i === 0 ? "/blog/" : `/blog/page/${i + 1}/`,
    component: path.resolve("./src/templates/blog-list.js"),
    context: { limit: postsPerPage, skip: i * postsPerPage, pageCount, currentPage: i + 1 },
  })
})

The template query uses limit: $limit, skip: $skip from GraphiQL and the data layer. For tag pages, query group(field: ...) and create one page per fieldValue with context: { tag }.

Stand-in: slugs and pages from data

This stand-in is not Gatsby. It mimics onCreateNode (adding fields.slug) and createPages (calling createPage with context), including previous and next links.

JS Stand-in: createPages with previous and next

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

No output.

Stand-in: pagination context

JS Stand-in: paginated list pages

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

No output.

Common mistakes

  • Relative template path. component must be an absolute path; use path.resolve or require.resolve.
  • Missing / at the start of path. Paths begin with a slash.
  • Huge context objects. Context is stored per page; pass IDs, not whole nodes.
  • Not handling result.errors. Without it, a failed query creates zero pages and the error is hard to spot.
  • Duplicate paths. Two posts with the same slug overwrite each other. Make slugs unique.

When a template page seems stuck on old data in development, restart gatsby develop. Changes to gatsby-node.js are not hot reloaded.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which API runs once for every node and is used to add a slug?

    onCreateNode receives each node, and createNodeField adds data to it under fields.
  2. 2. What are the three required options of createPage?

    path (URL), component (template file) and context (variables) define a page. Context is technically optional but practically always used.
  3. 3. How does a template read context values?

    Every context key can be used as a $variable and also appears in props.pageContext.
  4. 4. Why should context stay small?

    Pass IDs and the template can query the rest.

Summary

  • onCreateNode plus createNodeField adds a slug; createPages loops over query results.
  • createPage({ path, component, context }) creates one page per item, using an absolute template path.
  • Context keys become GraphQL variables in the template's page query.
  • Previous/next links, pagination and tag pages are all just more createPage calls.
  • Handle result.errors, avoid duplicate paths and keep context small.

Next: Source Plugins and gatsby-source-filesystem