This page looks best with JavaScript enabled

Create Your Blog Site With Gatsby.js Static Site Generator

 ·  ☕ 13 min read  ·  ✍️ Adesh

We are going to create a blog site something like below.

Blog Post listing page

gatsby static site generator

Navigating to blog post detail

create blog using gatsby

Table of Contents

  1. What are static site generators?
  2. Gatsby.js Introduction.
  3. What are the prerequisites for Gatsby.js?
  4. How to setup Gatsby.js?
  5. Install and Config Gatsby plugins.
  6. How to setup static site layout?
  7. How to create blog posts by Gatsby?
  8. Use GraphQL to query posts.
  9. Blog post listing using GraphQL.
  10. Create blog pages using Gatsby’s Node.js createPage API.
  11. Designing the blog template.
  12. Summary

1. What are static site generators?

Static site generators are not new. But they are now in the trend. A lot of blogging or personal sites are generated by these generators.

A static site generator takes source files and generates an entirely static website.

Static site generators are command-line tools that shift the creation of the final HTML page forward from the point the user requests it to the point you write the content.

Click here to see various generators –– StaticGen

This offer several advantages.

  • Static sites are incredibly fast, as there is no server round-trip and database calls.
  • Easy to learn and setup in few minutes.
  • It overcomes the security issues of any dynamic site. Static sites are secure and reliable.
  • These can be integrated with Git version control and make it live site on static web hosts like Netlify, Surge.Sh or ZEIT etc.

2. Gatsby.JS Introduction

Gatsby is a blazing fast modern site generator for React. It uses React, which means that everything is built with components, and allows it to benefit from React’s approach to DOM rendering. This means it can be picked up quickly by developers who have worked with React, but for those unfamiliar with it, learning React will be necessary.

It also utilises GraphQL at build time to retrieve data and content from data sources, which provides a modern, consistent interface to ensure that each page receives the exact data needed when it is built.

Finally, it will build pages as progressive single page apps, meaning that the entire site is downloaded and subsequent navigation is immediate.

3. What are the prerequisities for Gatsby.js?

Gatsby.js prerequisites are Node.js and npm on your machine.

Note: Gatsby’s minimum supported Node.js version is Node 8, but feel free to use a more recent version.

Check Node.js and npm installation

Open your Mac terminal window.

Type and run node --version to check the node.js version.

Type and run npm --version to check the npm version.

If you don’t have Node.js and npm installed on your machine, you can download it from below link.

Download Node.js

Check Git Installation

Gatsby.js requires Git. When you install a Gatsby “starter” site, it uses Git behind the scenes to download and install the required files for your starter. You will need to have Git installed to set up your first Gatsby site.

If you don’t have Git installed on you machine, you can install it from below links:-

4. How to setup Gatsby.js?

The Gatsby Cli is available via npm and should be installed globally by running these commands.

1
npm install -g gatsby-cli

OR

1
sudo npm install -g gatsby-cli

Once you installed Gatsby Cli on your machine, now it’s time to setup your static site project. Run this command to setup your project.

1
gatsby new static-blogsite

This command will download all the necessary packages and setup the project in few moments.

Once everything is setup successfully, it’s time to go to the project directory and start the development server with this command:

1
cd static-blogsite
1
gatsby develop

It will start the Gatsby server and launch the website in the browser.

static site generator with Gatsby.js and netlify

gatsby develop command

Gatsby default starter

Gatsby Default Starter

We have successfully setup static site and launched the static web site in the browser.

5. Install and Config Gatsby Plugins

Install Gatsby plugins

In order to setup our static site layout, we are going to install following Gatsby plugins. These are:

Let’s install them in our project. Run this command in your terminal.

1
npm install --save gatsby-transformer-remark gatsby-source-filesystem

once these plugins are installed, next we have to configure them in our project.

Configure Gatsby plugins

Let’s open your project in Visual Studio Code, and select gatsby-config.js file. Go to the plugins section, and add code like below:

gatsby-config.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
module.exports = {
  siteMetadata: {
    title: `ZeptoBook - Static site`,
    description: `Each week I will create and launch new websites and apps. Posting each here to showcase their story and purpose.`,
    author: `ZeptoBook`,
  },
  plugins: [
    `gatsby-plugin-react-helmet`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `src`,
        path: `${__dirname}/src/`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images/`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `posts`,
        path: `${__dirname}/src/blog-posts/`,
      },
    },
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        // CommonMark mode (default: true)
        commonmark: true,
        // Footnotes mode (default: true)
        footnotes: true,
        // Pedantic mode (default: true)
        pedantic: true,
        // GitHub Flavored Markdown mode (default: true)
        gfm: true,
        // Plugins configs
        plugins: [],
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `gatsby-starter-default`,
        short_name: `starter`,
        start_url: `/`,
        background_color: `#663399`,
        theme_color: `#663399`,
        display: `minimal-ui`,
        icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
      },
    },
    // this (optional) plugin enables Progressive Web App + Offline functionality
    // To learn more, visit: https://gatsby.dev/offline
    // `gatsby-plugin-offline`,
  ],
}

6. How to setup static site layout?

Since we are creating a blog site, it has the following parts like –– a blog home page –– display blog post title on homepage & each blog post detail on a separate page. In this section, we will learn about how to use layout for the styling of our static site.

Every website has some layout like a global header and footer, navbar or sidebar, etc. Gatsby uses the Layout component to design the default layout of the website. You can see, there are two files in the components folder –– layout.js & layout.css.

header.js

Let’s change the default header component. Open header.js in src->components folder, and edit code same as below:

header.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { Link } from "gatsby"
import PropTypes from "prop-types"
import React from "react"

const Header = () => (
  <div
    style={{
      background: 'black',
      marginBottom: '1.45rem',
      marginTop:'0px',
      display:'block',
      boxShadow:'0px 0px 7px black',
    }}
  >
    <div
      style={{
        margin: '0 auto',
        maxWidth: 960,
        padding: '1.45rem 1.0875rem',
      }}
    >
      <h1 style={{ margin: 0, textAlign:'center' }}>
        <Link
          to="/"
          style={{
            color: 'white',
            textDecoration: 'none',
          }}
        >
          ZeptoBook - Static Site Blog
        </Link>
      </h1>
    </div>
  </div>
)
export default Header

index.js

Once we created our header component, let’s edit index.js page.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import React from 'react'
import Helmet from 'react-helmet'
import Header from '../components/Header'
import { graphql } from "gatsby"

export default () => {
  return (
    <div>
      <Helmet
      title="ZeptoBook - Static Site Blog"
      meta={[
        { name: 'description', content: 'Sample' },
        { name: 'keywords', content: 'sample, something' },
      ]}
    />
    <Header />
    <div
      style={{
        margin: '0 auto',
        maxWidth: 960,
        padding: '0px 1.0875rem 1.45rem',
        paddingTop: 0,
      }}
    >
  </div>
</div>
  )
}

Gatsby provides React Helmet <Helmet /> component. With this react component, you can add –– title, meta description, etc. in the static Html page.

We also imported <Header /> component, and placed it after the <Helmet /> component.

If you see in your browser, you will new header on your page.

7. How to create blog posts by Gatsby?

Gatsby can use Markdown files to create pages on your website. Gatsby uses this plugin gatsby-source-filesystem to read and understand Markdown files and create pages from them automatically.

Markdown file has an extension of .md. Let’s create Markdown files for our blog posts. Create a blog-posts sub-folder under the foldersrc and create three Markdown files.

post-1.md

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
---
title: "Gatsby First Blog Post"
date: "2019-09-01"
author: "Adesh"

---

This is my first Gatsby blog post.

You've probably heard how paramount blogging is to the success of your marketing. But it's important that you learn how to start a blog and write blog posts for it so that each article supports your business.

Without a blog, your SEO can tank, you'll have nothing to promote in social media, you'll have no clout with your leads and customers, and you'll have fewer pages to put those valuable calls-to-action that generate inbound leads.

post-2.md

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
---
title: "Gatsby Second Blog Post"
date: "2019-09-02"
author: "Adesh"

---

This is my second Gatsby blog post.

Writing a blog post is a little like driving; you can study the highway code (or read articles telling you how to write a blog post) for months, but nothing can prepare you for the real thing like getting behind the wheel and hitting the open road. Or something.

post-3.md

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
---
title: "Gatsby Third Blog Post"
date: "2019-09-03"
author: "Adesh"

---

This is my third Gatsby blog post.

A brilliant header, clean sidebar, and minimalist footer can go a long way towards making a blog look good. But the one area that’s often overlooked in blog design is the post styling.

Make sure, you have configure the blog folder path correctly in gatsby.config.js file. It should be like below:

gatsby-source-filesystem in gatsby.config.js file

gatsby.config.js

8. Use GraphQL to query posts

GraphQL is a query language like SQL. Gatsby uses GraphQL at build-time and not for live sites. If you noticed earlier while creating the project, I had shared two links in the screenshot. First was –– http://localhost:8000/  and http://localhost:8000/___graphql.

It means you don’t need to set up anything about GraphQL. Gatsby set it up automatically and provided you the link. You can open this link in the browser and run the following command to pull up all your blog data.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
{
   allMarkdownRemark {
     totalCount
     edges {
       node {
         frontmatter {
           title
           date
           author
         }
         excerpt
       }
     }
   }
 }

The result would be something like this.

gatsby GraphQL query

GraphQL

This query will return the list of all blog posts.

Here, two Gatsby plugins –– gatsby-source-filesystem and gatsby-transformer-remark play a vital role to fetch this data from our Markdown (.md) files.

Specially, plugin gatsby-transformer-remark transforms all Markdown file nodes into MarkdownRemark nodes which can be queried for their content.

9. Blog post listing using GraphQL

It’s time to integrate GraphQL query data and show the blog post listing on the home page –– Index.js.

Import GraphQL

Create blog post listing template using GraphQL result data

1
2
3
4
5
6
7
8
9
<h4>Total Posts: {data.allMarkdownRemark.totalCount}</h4>
      {data.allMarkdownRemark.edges.map(({ node }) => (
        <div key={node.id} className="article-box">
        <h3 className="title">{node.frontmatter.title}</h3>
        <p className="author">{node.frontmatter.author}</p>
        <p className="date">{node.frontmatter.date}</p>
        <p className="excerpt">{node.excerpt}</p>
      </div>
      ))}

GraphQL query in component

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
export const query = graphql`
  query {
    allMarkdownRemark {
      totalCount
      edges {
        node {
          id
          frontmatter {
            title
            date
            author
          }
          excerpt
        }
      }
    }
  }
`

Styling blog listing template

Create index.css in src/pages folder and import it in index.js file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
.article-box{
    margin: 1.5em 2em;
    padding: 2em;
    box-shadow: 0px 0px 6px darkseagreen;
    font-family: 'Helvetica';
    border: solid 2px darkgoldenrod;
}
.title{
    font-size: 2em;
    color: white;
    margin-bottom: 0px;
}
.author, .date{
    margin:0px;
}
.date{
    color: rgb(165, 164, 164);
}
.excerpt{
    margin-top: 0.6em; }

Looks beautiful and blaze fast. Now, our home page with blog posts listing is ready. Now, it’s time to create blog page for its details.

10. Create blog pages using Gatsby’s Node.js createPage API

Gatsby can create dynamic pages using powerful Node.js createPage api. This API is available in the gatsby-node.js file in the root directory of your project.

Use the GraphQL to query Markdown file data as below. Next, use the createPage action creator to create a page for each of the Markdown files using the blogTemplate.js

Gatsby APIs has two method for creating pages from Markdown files –– createPages & onCreateNoe.

This onCreateNode function will be called by Gatsby whenever a new node is created (or updated).

Stop and restart the development server. As you do, you’ll see quite a few newly created nodes get logged to the terminal console.

Use this API to add the slugs for your markdown pages to MarkdownRemark nodes.

createPages handle GraphQL data and map the query result to pages. Below is the complete implementation of both APIs in gatsby-node.js.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
 * Implement Gatsby's Node APIs in this file.
 *
 * See: https://www.gatsbyjs.org/docs/node-apis/
 */

// You can delete this file if you're not using it

const path = require(`path`)
const { createFilePath } = require(`gatsby-source-filesystem`)
exports.onCreateNode = ({ node, getNode, actions }) => {
  const { createNodeField } = actions
  if (node.internal.type === `MarkdownRemark`) {
    const slug = createFilePath({ node, getNode, basePath: `pages` })
    createNodeField({
      node,
      name: `slug`,
      value: slug,
    })
  }
}
exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions
  const result = await graphql(`
    query {
      allMarkdownRemark {
        edges {
          node {
            fields {
              slug
            }
          }
        }
      }
    }
  `)
  result.data.allMarkdownRemark.edges.forEach(({ node }) => {
    createPage({
      path: node.fields.slug,
      component: path.resolve(`./src/templates/blogTemplate.js`),
      context: {
        // Data passed to context is available
        // in page queries as GraphQL variables.
        slug: node.fields.slug,
      },
    })
  })
}
Note –– line 14, we have ‘./src/templates/blogTemplate.js’ path. This is our blog template, where we will show blog details when user click on blog title on blog listing page.

Let’s create this template file as well.

11. Designing the blog template

In the above section, I mentioned the fileblogTemplate.js. Let’s create this file in src/templates folder to show our blog detail page.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import React from "react";

export default ({ data }) => {
  const post = data.markdownRemark;
  return (
    <div style={{margin: '2em'}}>
      <h1>{post.frontmatter.title}</h1>
      <h4 style={{color: 'rgb(165, 164, 164)'}}>{post.frontmatter.author} <span style={{fontSize: '0.8em'}}> -{post.frontmatter.date}</span></h4>
      <div dangerouslySetInnerHTML = {{ __html: post.html }}/>
    </div>
  );
};

export const query = graphql`
  query PostQuery($slug: String!) {
    markdownRemark(fields: { slug: { eq: $slug } }) {
      html
      frontmatter {
        title
        author
        date
      }
    }
  }
`;

This template will consume GraphQL query data.

Note –– I have changed below line to make title as link in pages/index.js file.
1
<h3 className="title">{node.frontmatter.title}</h3>

changed to

1
<Link to={node.fields.slug} style={{textDecoration: 'none', color: 'inherit'}}><h3 className="title">{node.frontmatter.title}</h3></Link>

12. Summary

In this blog, we have learned about how to create static blog site using Gatsby and React.js. Gatsby is powered by GraphQL which make it blazing fast, and there is no download time as all pages are served statically. You can download the code by clicking on below download button.

Download Code

Further Reading

Array.Prototype.Flat() or ES2019 Array Flat() function

Type Inference In TypeScript

How Change Detection Works In Angular

Share on

Adesh
WRITTEN BY
Adesh
Technical Architect