How to create pages dynamically in Gatsby using MDX

3 min read

How to create pages dynamically in Gatsby using MDX

In this post, we will be looking into how to create pages programmatically using MDX in Gatsby.

To get up and running, we need to install a couple of plugins

npm i gatsby-plugin-mdx @mdx-js/mdx @mdx-js/react

Then we need to configure gatsby-mdx inside gatsby-config.js

So first we need to resolve the plugin gatsby-plugin-mdx because we also want to pass in options object which defines what layout that we want to use in our MDX files.

Note: require.resolve give us the absolute path name.

As a result, any MDX files that we load will be loaded into the Layout.js template that we defined in the gatsby-config.

gatbsy-config.js

1
plugins: [
2
{
3
resolve: "gatsby-plugin-mdx",
4
options: {
5
defaultLayouts: {
6
default: require.resolve("./src/components/Layout.js"),
7
},
8
},
9
},
10
];
11

Now that we have installed the plugin, the plugin will look for mdx files in the pages or posts directory which we defined in gatsby-config.

So to get the post pages into gatsby, we are going to use another plugin gatsby-source-filesystem

npm i gatsby-source-filesystem

to get them to the data layer so that we can access them.

The gatsby source file system is a way to use local files as part of the graphql data layer.

Once it gets installed, we need to update gatsby config to resolve source filesystem plugin

gatsby-config.js

1
plugins: [
2
{
3
resolve: "gatsby-plugin-mdx",
4
options: {
5
defaultLayouts: {
6
default: require.resolve("./src/components/Layout.js"),
7
},
8
},
9
},
10
{
11
resolve: "gatsby-source-filesystem",
12
options: {
13
name: "posts",
14
path: `${__dirname}/content/posts`,
15
},
16
},
17
];

As a result, it will load anything that it finds in the path /content/posts as part of the data layer, and because we have gatsby MDX plugin installed it's going to look for MDX files and transform those into graphql nodes.

The whole reason for using MDX is because we want to add some sort of interactivity in the markup generated pages.

Now that we added configuration to look for files in the system and transform them to graphql nodes, we would need to generate those post files as pages programmatically using gatsby API createPages by configuring that in gatsby-node.js.

Gatsby in itself has a couple of available APIs that can be used to extend how gatsby works, inside of those you can export a function that is the same name as one of the hooks that gatsby looks for. As a result, gatsby will do those instructions at the build phase.

In this case, we want to create pages so we use exports.createPages and because we are going to load data we make the function async.

Gatsby will give us a couple of utility methods such as actions, graphql helper and reporter(which can be used in case you want to put something in the console, it's a gatsby internal kind of console.log)

gatbsy-node.js MDX

1
exports.createPages = async ({ actions, graphql, reporter }) => {
2
const result = await graphql(`
3
query {
4
allMdx {
5
nodes {
6
frontmatter {
7
path
8
}
9
}
10
}
11
}
12
`);
13
14
if (result.errors) {
15
reporter.panic("failed to create posts ", result.errors);
16
}
17
18
const pages = result.data.allMdx.nodes;
19
20
pages.forEach((page) => {
21
actions.createPage({
22
path: page.frontmatter.path,
23
component: require.resolve("./src/templates/postTemplate.js"),
24
context: {
25
pathSlug: page.frontmatter.path,
26
},
27
});
28
});
29
};

In the createPage function, we will use graphql helper to fetch the nodes from the data layer by passing a graphql query as you can see in the snippet above.

Then, we create the pages using actions.createPage as we loop through these pages that came back as an array to generate them programmatically as you can see in the screenshot below

allmdx-query

actions.createPage takes an options object as a parameter that has 3 properties: path, component and context. Path is what we have defined in the MDX frontmatter. Component takes in the path to the template you want to use for these pages. Below is a sample snippet used as page template.

1
import { graphql } from "gatsby";
2
import { MDXRenderer } from "gatsby-plugin-mdx";
3
import React from "react";
4
5
import Layout from "../components/Layout";
6
7
export const query = graphql`
8
query ($pathSlug: String!) {
9
mdx(frontmatter: { path: { eq: $pathSlug } }) {
10
frontmatter {
11
title
12
path
13
}
14
body
15
}
16
}
17
`;
18
19
const Post = ({ data: { mdx: post } }) => {
20
const { title } = post.frontmatter;
21
const { body } = post;
22
return (
23
<div>
24
<Layout>
25
<h1>{title}</h1>
26
<MDXRenderer>{body}</MDXRenderer>
27
</Layout>
28
</div>
29
);
30
};
31
32
export default Post;

Context takes in an object with pathSlug as its property which value is the page path.

Once we finish adding the above, now we can add interactivity to our MDX pages which would look like this

1
---
2
path: "/blog/hello-world"
3
date: "2020/01/01"
4
title: "Hello World"
5
summary: "hello world post"
6
---
7
8
import Counter from "../../../src/components/Counter";
9
10
Hello World
11
12
<Counter />
mdxpage-example

Following the post and you can find a starter repo here that shows usage of MDX pages

If you found this post helpful, then you will love this one as it shows you how to add syntax highlighting to MDX files.