Creating Rest API endpoints to my Gatsby blog
Learn how to add API endpoints to Gatsby v3 using the onPostBuild method and create JSON files with a global variable
Gatsby is a popular static site generator that is built on React, and it’s the one that I use to create this blog. With its powerful plugin system, it allows developers to easily add features to their sites.
One feature that can be added is API endpoints, which can be used to serve JSON data to the client.
In this post, we will look at how to add API endpoints to Gatsby v3 by modifying the
First post of 2023, let’s go!!
In a Gatsby site, the data that is used to build pages is typically sourced from a variety of sources, such as
Markdown files or a headless CMS.
In my case, all my posts come from
Markdown files, and I have some custom scripts to match related posts, get the blog post comments, etc.
Since all my data is stored “offline”, if I want to access it in another aplication I would have to pretty much scrape my own website, and that’s not good.
If I create an API endpoing for my blog, then I can expose all data that is currently already public and displayed as
HTML, but provide it as a “raw” JSON data.
To add API endpoints to a Gatsby site, we need to take advantage of the
onPostBuild lifecycle method in the
gatsby-node.js file. This method is called after the site has been built, and allows us to perform additional actions, such as creating JSON files.
Since I do a lot of custom scripting in all my pages, we are using a global variable called
jsonFiles that will dynamically populate with data from the
This will be used to store the data that we want to use to create the JSON files then loop through each path in the
jsonFiles object and use the createPage action to create a new page for each path.
Here is an example of how I’m doing it:
Consuming the data from the API endpoints
Once the API endpoints have been created, the next step is to consume the data from the client side. This can be done by using the
Here is an example of how to use
fetch() to get the data from the endpoint for this blog post:
Adding API endpoints to a Gatsby site is a simple task, but can enhance the possibilities of your website.
I will soon (I hope) share what I plan to do with my own API 👀
That’s all I have for you guys today, see you in the next one!