Programmatic Page Creation
7 min read
Programmatic Page Creation in Gatsby 📄⚙️
Welcome, intrepid developer! Today, we're diving into one of Gatsby's most powerful features: creating pages automatically. Imagine you have a blog with hundreds of posts. Are you going to create a new file for each one by hand? I surely hope not! That's where programmatic page creation comes to the rescue.
The Problem: Manually creating a new page file for every single blog post, product, or portfolio piece is tedious, error-prone, and just not scalable. As your site grows, managing these files becomes a nightmare.
The Solution: We can write code that generates these pages for us during Gatsby's build process. This means we can pull data from anywhere—Markdown files, a headless CMS, a database—and tell Gatsby to create a page for each piece of data.
1. Introduction to the Node API: The gatsby-node.js File 🤝
At the heart of programmatic page creation is a special file called gatsby-node.js.
What is gatsby-node.js?
This file is a bit like the control room for your Gatsby site's build process. It's where you can tap into Gatsby's Node.js APIs to customize and extend the site generation. The code in this file runs once at build time on the server, not in the user's browser. This is where we'll instruct Gatsby on how to create our pages.
Think of it this way: if your Gatsby site is a factory, gatsby-node.js is the foreman giving instructions on the assembly line before the final product (your static site) is shipped out.
The createPages API
One of the most important APIs available in gatsby-node.js is createPages. Gatsby calls this function when it's time to, you guessed it, create pages. This is our entry point for generating pages dynamically.
Here's what a barebones gatsby-node.js file looks like:
// gatsby-node.js
exports.createPages = async ({ graphql, actions }) => {
// This is where the magic will happen!
};exports.createPages: We are exporting a function that Gatsby will execute.async: We useasyncbecause we'll be fetching data, which is an asynchronous operation.graphql: A function that allows us to run GraphQL queries to fetch our data.actions: An object containing functions (we call them "actions") that let us manipulate the Gatsby build. The one we care most about iscreatePage.
🧠 Fun Fact: The
gatsby-node.jsfile is one of the few places in a Gatsby project where you can write server-side Node.js code freely, giving you access to the file system, network requests, and the vast Node.js ecosystem.
2. Querying Data Dynamically for Template Generation 🎣
Before we can create pages, we need data for them. Let's say we have a series of Markdown files for our blog posts. We need to query for those files so we can create a page for each one.
The Problem: How do we get the necessary information (like the URL slug) for each blog post from our data source into our gatsby-node.js file?
The Solution: We use the graphql function that Gatsby provides within the createPages API.
Here’s how you would query for all your Markdown files to get their slugs:
// gatsby-node.js
exports.createPages = async ({ graphql, actions }) => {
const { data } = await graphql(`
query {
allMarkdownRemark {
nodes {
frontmatter {
slug
}
}
}
}
`);
// We'll use this data in the next step!
};In this example:
- We use a GraphQL query to get all nodes of type
MarkdownRemark(assuming you havegatsby-transformer-remarkset up). - For each Markdown file, we're asking for the
slugfield from itsfrontmatter. Theslugwill be used to create the URL for the page (e.g.,/blog/my-first-post).
This query returns a promise, which is why we use await. The result is an object containing our data, which we can then loop over.
3. The createPage Action: Spawning Pages on the Fly ✨
Now that we have our data, we can start creating the pages. This is where the createPage action comes into play.
The Problem: We have a list of slugs, but how do we tell Gatsby to actually generate an HTML page for each one, and which component to use as the template?
The Solution: We loop through our queried data and call the createPage action for each item.
Let's expand on our previous example:
// gatsby-node.js
const path = require('path');
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions;
const blogPostTemplate = path.resolve(`src/templates/blog-post.js`);
const { data } = await graphql(`
query {
allMarkdownRemark {
nodes {
frontmatter {
slug
}
}
}
}
`);
data.allMarkdownRemark.nodes.forEach(node => {
createPage({
path: `/blog/${node.frontmatter.slug}`,
component: blogPostTemplate,
context: {
// Data passed to context is available in page queries as GraphQL variables.
},
});
});
};Let's break down the createPage call:
path: This is the URL for the new page. We're constructing a path like/blog/my-first-post. This is what users will see in their browser's address bar.component: This is the absolute path to the React component that will serve as the template for this page. We use Node's built-inpath.resolveto make sure we have the correct path. This template component is responsible for displaying the content of a single blog post.context: An object where we can pass data down to the page component. This is crucial, and we'll explore it in the next section.
4. Passing Context Objects and Using GraphQL Variables 🎁
We've created pages, but they are all empty shells. How does the blog-post.js template know which blog post's data to display?
The Problem: The page at /blog/my-first-post needs to fetch only the data for "My First Post". The page template is a generic component; it needs a unique identifier to query for its specific data.
The Solution: We pass a unique identifier (like the slug) down to the page template via the context object in the createPage action. This context data is then available as a GraphQL variable in the page template's query.
Step 1: Pass the slug in the context
Let's update our gatsby-node.js:
// gatsby-node.js
const path = require('path');
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions;
const blogPostTemplate = path.resolve(`src/templates/blog-post.js`);
const { data } = await graphql(`
query {
allMarkdownRemark {
nodes {
frontmatter {
slug
}
}
}
}
`);
data.allMarkdownRemark.nodes.forEach(node => {
createPage({
path: `/blog/${node.frontmatter.slug}`,
component: blogPostTemplate,
context: {
slug: node.frontmatter.slug, // Pass the slug here!
},
});
});
};Step 2: Use the slug in the page template's query
Now, inside src/templates/blog-post.js, we can write a special kind of GraphQL query called a "page query" that accepts variables.
// src/templates/blog-post.js
import React from 'react';
import { graphql } from 'gatsby';
const BlogPost = ({ data }) => {
const post = data.markdownRemark;
return (
<div>
<h1>{post.frontmatter.title}</h1>
<div dangerouslySetInnerHTML={{ __html: post.html }} />
</div>
);
};
export const query = graphql`
query($slug: String!) {
markdownRemark(frontmatter: { slug: { eq: $slug } }) {
html
frontmatter {
title
}
}
}
`;
export default BlogPost;Let's look closely at the query:
query($slug: String!): This line defines a GraphQL variable named$slugof typeString. The!means it's a required variable.markdownRemark(frontmatter: { slug: { eq: $slug } }): This is the crucial part. We are telling GraphQL to find the onemarkdownRemarknode whoseslugin the frontmatter is equal (eq) to the value of the$slugvariable we received from thecontext.
And that's it! Gatsby connects the dots: the slug from the context in gatsby-node.js is passed into the $slug variable in the template's page query. The template then receives the exact data it needs as props. 🪄
This entire process happens at build time, resulting in a super-fast, pre-rendered static site where every blog post has its own HTML page, ready to be served instantly.
For Further Reading 📚
- Official Gatsby Documentation on
gatsby-node.js: Gatsby Node APIs - Creating Pages from Data Programmatically: Creating pages from data
createPageAction Reference: Actions | Gatsby- Using GraphQL Variables in Page Queries: GraphQL Page Queries
Challenge
You are tasked with programmatically generating product detail pages for an e-commerce site. Your data source is allProductsJson, which contains a list of all products.
Inside the gatsby-node.js file, complete the createPages export. Your implementation must:
- Asynchronously query for the
idandslugof every product from theallProductsJsondata source. - Iterate through each product returned from the query.
- For each product, call the
createPageaction. - Configure the
createPagecall with the following properties:path: Use the product's slug to create a URL like/products/your-product-slug.component: Use the provided absolute path for the product page template.context: Pass an object containing the product'sid. Thisidwill be used by the template to query for that specific product's full details.
Expected result
Your gatsby-node.js file should correctly export the createPages function that queries for product data and uses the createPage action to generate a page for each product.
const path = require('path');
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions;
const productTemplate = path.resolve('./src/templates/product-template.js');
const result = await graphql(`
query {
allProductsJson {
nodes {
id
slug
}
}
}
`);
if (result.errors) {
throw result.errors;
}
const products = result.data.allProductsJson.nodes;
products.forEach(product => {
createPage({
path: `/products/${product.slug}`,
component: productTemplate,
context: {
id: product.id,
},
});
});
};