Creating Pages with the createPages API
Learn how to programmatically create pages in Gatsby without adding page components to the pages directory.
Why we need the createPages
API
Until this point, we only knew one way of creating pages in Gatsby projects—creating and exporting a page component in the pages
directory. While this seems like the best way to go, it has some limits, too.
Let’s consider our blog posts’ detail pages. We recall that clicking any of our posts to open the detail page redirects to a 404. This is because we have not built a page for it yet. Now, we can think of going into the pages
directory and creating pages for each of our Markdown blog posts. This is not ideal in any way because we may end up having up to ten or more blog posts, and we cannot create page components for each.
For the case above, we need a way to fetch the blog posts and create a page for each of them using code. This process must be run at build time, making the gatsby-node.js
file the perfect (and the only) place to house such code.
This brings us to the createPages
node API.
The createPages
API
This Gatsby node API allows us to programmatically create pages during the build. It accepts an object which contains the following:
-
graphql
: This function accepts a query block for fetching data used in building out the pages. -
actions
: This is also an object. There are many different actions in Gatsby, but the one we’re interested in now is thecreatePage
action.
The createPage
function
This is the function that we use to create the page. It accepts an object containing the data required to create a page:
-
path
: It is a relative path that leads to the new page. It must begin with a/
. -
component
: It is the path to a valid JSX component for this page. -
context
: It is data that needs to be passed into the component declared above. Inside the component, this data can be accessed through thepageContext
prop. It is also passed into any page queries in the component that uses variables.
Building the page template component
When using createPages
, Gatsby requires a component to use a template to build out these pages. In our case, we need a component that displays a post’s title, description, published date, featured image, and then the body of the post. So, let’s build it.
We head over to the /templates
directory, where we can see an existing using-dsg.js
file. A postDetail.js
file has already been created.
Get hands-on with 1400+ tech skills courses.