Supercharge Your JAMStack Website With Gatsby, Contentful, and Netlify
Here we will get into simple steps on how u can create your next website or blog with easily integrated content management and supercharge your website overall.
There has been lot of debate going on with the static site generators due to rise of JAMStack application. Despite the debate Gatsby has been widely used and have decent numbers of stars in Github. You can find the top static generators collection here.
🔋There are number of noticeable advantage of Gatsby. Some are:
- Less configuration needed, most done out of the box.
- SEO, Speed and performance optimization.
- Great community, nice documentation and growing plugin ecosystem.
- Ultimately better developer experience.
In this article we will be covering on showing how we can set up a system for managing content on any page of our Gatsby site. We will be making use of gatsby-node API to pull in content from Contentful and dynamically generate pages with it. We can also use Contentful data on any existing page via graphql queries.
🏋🏽♂️ Setting-up Gatsby
We’ll need the gatsby-cli tool to get started. Run npm i -g gatsby in your terminal and once that has run, create a new project with the command
$ gatsby new gatsby-demo
This command will create a new Gatsby project in your desired location path. Then we can locally run the project with gatsby develop. Now we can see our Gatsby starter homepage is running on localhost:8000
Let’s make a minor tweak to our code and replace the following code with the following code.
Let’s move to the Pages folder and find page-2.js and rename it to siteposts.js. Gatsby uses files in the pages folder as route name and it will make the exported React component available on the defined route. You may be familiar to this if u have used Nuxt or Next before. This means we have a /siteposts route. In the meantime, let’s also change a few values inside of gatsby-config.js file as well.
siteMetadata: {
title: `My Awesome Post`,
description: `An awesome post does have some cool description.`,
author: `YOUR_NAME`,
},
This is going great till now. We have made a basic setup. We will now move ahead with creating new account inside Contentful.
✍🏼 Making Content with Contentful
After you create an account in Contentful you can find create space in top left hidden inside a hamburger menu and choose a free option available there or choose Gatsby starter for Contentful if you don’t want to enter your payment card details. Go to content model and Add content type to kick start.
After we create our content type, we will add some fields that we desire. Fields are the building block for our content. If we have a post there would obviously be the title, the body, the tags, image or may be date field. This will generate a form that we can fill later on when we start to create actual post itself.
In the form let’s add some desired fields just like creating schema for our backend. For this post we can add fields like Heading, Title, Image and description of our post. If u are totally confused whats going on you can also take a reference from the documentation here. We will first field starting with heading.
We will also add more content model as per we discussed earlier. And all the created fields we can mark as mandatory field for our demo. After adding all fields we at last can add up a Slug.
A ‘slug’ is the unique identifying part of a web address, such as the
/tutorial/part-seven
part of the pagehttps://www.gatsbyjs.org/tutorial/part-seven/
We will choose a normal text and call it a slug. Rather than creating a field type we will click on Create and configure. On the next screen go to apperance tab and select slug as the way the field should be displayed.
Note: The Validation tab select unique fields to be sure that no two blog posts have the same slugs.
After we have it all ready for the fields. Let’s take a peek on what our data looks like now.
This exactly can be represent like schema made to store into our database. We can create models such as E-commerce, Entertainment, Food, Documentation, Product pages and more.
We will head towards Save button for saving our current progress on top right. I will add couple of post from the button Content placed in the top navigation bar. We have our first couple of posts ready and it’s time to pull them into our Gatsby site. Let’s take a look at our content page.
🤹🏽 Using content from Contentful
Let’s generate an API key going through the settings. Where we will be using Contentful’s Content Delivery API since we want to retrive our published data. Inside our gatsby-config.js file lets add the following snippet in the configuration object to the plugins array:
{
resolve: `gatsby-source-contentful`,
options: {
spaceId: `SPACE_ID`,
accessToken: `CONTENT_DELIVERY_API_KEY`
}
}
After we place this object lets restart our development server again. When the server restarts, gatsby-source-contentful GraphQL queries will be available to use.
Now we can test if everything is working fine by using the GraphiQL playground that Gatsby provides for us. Lets open up http://localhost:8000/___graphql in our browser and run the query below by pasting it into the left window on the page. The query name is allContentfulSitePost because our content model is called Site Post.
query MyQuery {
allContentfulSitePost {
nodes {
heading
description {
json
}
image {
file {
url
}
}
subheading
slug
}
}
}
The gatsby-source-contentful plugin handles all the behind the scenes fetching from the Contentful API using the keys we provided in the gatsby-config file. It then makes a semantically named GraphQL query available to us.
If it all works, you should see the content you added in the results window to the right of the GraphiQL window in JSON format. Like shown in the screenshot below:
We have now successfully connected our Gatsby blog with our Contentful data. Gatsby provides us with a file called gatsby-node.js. This file can be used to dynamically add pages to your site. When Gatsby runs, it will look at the code and create any pages we tell it. In the gatsby-node.js file let’s place this snippet of code.
This module export function is called with createPages where it takes two parameters, Graphql and an action object. From there we extracted the createPage action then we called the same Graphql query we ran in the Graphql playground like we earlier did. We took the result for each result we then created createPage function. This function accepts a config object which Gatsby reads when rendering the page. We set it path to concatenated string “/siteposts” plus the slug we created for it as well.
If u have noticed we have referenced a template file at ‘./src/pages/siteposts.js’ we will be creating this file soon as well.
Now lets, kill your server and start it up again. If you enter a dud route like http://localhost:8000/some-random-route/ you’ll see Gatsby’s development 404 page. This page has a list of all the routes and as you can see the newly created pages have been set up as we see in the screenshot below:
Here you may have noticed each post has a unique route and are using slugs which looks so much better than using just ID strings in the URL. Also since Gatsby generates a static site which can have a sitemap its much better for SEO.
Lets now create a templates folder inside of the src folder and add a new file and name it siteposts.js. This will be our template component which we will use whenever Gatsby calls createPage function.
Now we can concentrate on building out the actual pages gatsby-node.js file every time. Also we need to restart the server as we are making frequent changes inside our server files.
We have exported our Graphql query which shall run this query at runtime and will pass a data prop to BlogPost containing the Contentful data. In this case we are querying a single post and passing the slug alongside as a filter parameter.
Basically we are asking for the post which matches the passed in slug (contentfulSitePost(slug: { eq: $slug })). This slug is made available to us because we passed it in as a page context in our gatsby-config.js.
Lets make a tweak to our siteposts.js inside our pages folder. Where we will map through the each post we took from Contentful via Graphql request. Lets look at the code we have here:
The query is the same that we used in gatsby-node.js to generate the blogpost pages. It fetches the data from Contentful data of the SitePosts type. Gatsby makes the result of the query available to us in the data object just as with the individual blogpost page. For this page though, we only need the id, heading, slug, description, subheading, image.
You can still add bit of styling needed as well.
🛰 Deploying to Netlify
Now, we have somewhat working blog post we have ready to deploy to Netlify. Its now time to show it and make available for everyone to access it. With Netlify this is really easy. Netlify integrates really well with GitHub.
Inside our project root path, run:
$ git init
Once we hit this command we have activated git. We will go to our GitHub repo called gatsby-contentful-sample-blog, then follow the commands for pushing to an existing repository.
$ git add .
$ git commit -m 'our initial commit'
$ git remote add origin git@github.com:YOUR_GITUHB_USERNAME/gatsby_demo.git
$ git push -u origin master
After we push our code to Github we will now head towards Netlify, where we will create a new account if we don’t have one yet.
Next, select a repo from the list provided. if you can’t find the repo we just created, select Configure the Netlify app on GitHub. This will open a popup allowing you to choose the repository we want to authorize for use with Netlify. After selecting our blog project, you’ll be redirected to the Netlify deploy screen and we should now be able to select the gatsby-demo as our filename repository.
As we can see, Netlify knows how to build Gatsby sites so you can just click the Deploy Site button at the end of the page.On Netlify click on Site Settings and then in the left menu, select Build & Deploy.
⚓️ Adding Webhooks to Netlify
As u have know we needed to kill the server and restart it to fetch data. we don’t want to trigger a redeploy manually every time someone adds or change content in Contentful. For this reason we will use Contentful’s hooks to trigger an automatic Netlify redeploy of our site.
With this approach when new pages will get added to our blog automatically for each new posts created. On Netify click on Site Settings and then in the left menu, select Build & Deploy. Look for the Add build hook button and click on it, giving the build hook a name and then click on Save.
Now copy the build-hook url and go back to your Contentful dashboard. Hit the settings drop down and select Webhooks. The Webhooks screen already has a template for Netlify in the bottom right. Let’s click on it.
In the above screenshot we have added a webhook POST URL, which we generated from Contentful.
Now when we go back to the Content page and add a new blog post. As soon as we hit publish, Contentful will make an API call to the build hook you provided. This will in turn, cause Netlify to redeploy your site. Gatsby will pull in the Contentful data all over again, which now includes the new post you added, and create a new page based on the new blog post.
From here you can still add more content and more pages much easily and expand more on the website we have. You also can take the reference to the code in my public repository here.
⌨️ Conclusion
With the combination of these stack you can seamlessly create a well functioning website or blog or any CMS related application. This approach is common and famously known as JAMStack.
— — — — — — — — — —Happy Hacking! — — — — — — — — —