Gatsby — Static Site Generator

Create a complete website in the time it usually takes to build a prototype.

What is Gatsby?

Gatsby is widely known as the Static Site Generator (SSG). It uses GraphQL to get data from anywhere. It uses React for templating and CSS for styling. It includes a Plugin Architecture. Gatsby generates static HTML pages using a combo of templates, components and data.

Why use Gatsby?

Use Gatsby for Speed, Security and Dev experience. Under the hood it uses Node, React and GraphQL.

Types of Websites

Static websites:

In static websites the website is hosted on a Web Host / CDN and whenever a page request is made to the server , it responds with the HTML,CSS and JS. For each new Page request we get HTML, CSS and JS in response.

Key points :

Use static HTML Pages ( with JS and CSS).

Pages uploaded to a CDN / Web Host.

Drawbacks:

Hard to update / maintain pages (re-writing a lot of the same code on every page).

Fresh request to the server for every page request ( slows website down ).

Generally do not contain dynamic data.

Factors: SEO Friendly: Yes, Speed: No, Easy to Update: No

Single Page Applications:

In Single Page Applications, A single server request is made for a blank html page which is sent back to the browser and then React/vue or anyother framework would control content, pages and data fetching from the browser.

Key points:

Typical React/ Vue Website

Only a single server request mode for the initial HTML Page (empty)

Everything else (routing, data) is handled by the SPA in the browser.

Drawbacks:

Web pages are not SEO Friendly (initial request is for a blank HTML page)

Factors: SEO Friendly: No, Speed: Yes, Easy to Update: Yes

Server Side Rendered (SSR) :

In Server side rendered web sites, HTML pages are built on the server upon page request and then sent back as response.

Key points :

Pages rendered on the server after every request.

Server sources data (eg: MongoDB ) & uses templates to render HTML Pages.

Resulting pages are sent back to the browser.

Drawbacks:

Fresh request needs to be made for every page.

Server can take time getting data and rendering Pages.

Factors: SEO Friendly: YES, Speed: No, Easy to Update: YES

Static Site Generator (Gatsby ) :

Static site Generation is a process where final html pages are compiled at the build time, not on the server on each request but before even the application is deployed to web. Here in Gatsby, we run Gatsby build to generate the static assets and then these assets are hosted on the Web Host/ CDN .

Key points:

static pages are compiled at the build-time (before deployment)

Gatsby sites / pages are made using React Components

Static pages are then deployed to the web

After initial request, the site behaves more like an SPA.

Factors: SEO Friendly: YES, Speed: YES, Easy to Update: YES

Getting Started with Gatsby Application

Initial Setup

To get started with Gatsby, you will need to have NodeJS and Git installed on your machine. With NodeJS, you can run your Gatsby JavaScript code outside of a web browser. You will also have access to its npm (node package manager) tool.

You can check if you have it installed by running npm -v and node –v in your terminal. The commands should return their respective versions. If not, head over to NodeJS website, download and install the latest version.

Install Gatsby CLI Globally

npm install -g gatsby-cli

Once the installation of Gatsby-cli installation is completed.

Build the Project using the following command

SYNTAX: gatsby new [PROJECT_DIRECTORY] [STARTER_URL]

gatsby new firstapp https://github.com/gatsbyjs/gatsby-starter-hello-world

Here we are using the Hello world starter template

firstapp in the above command indicates the app name

https://github.com/gatsbyjs/gatsby-starter-hello-world is the template URL.

default template is loaded if template url is not defined. Gatsby new firstapp -default

Folder structure

.cache and public folders are generated when gatsby develop is run in the terminal.

.cache folder is used by the Gatsby for cache.

node_modules will store the dependencies.

Public folder contains the Production ready application.

src folder will contain the folders for pages , components etc.

Once the app is ready, running Gatsby build would get the production ready code in the public folder.

Static folder should not be used directly to store the static assets like images or css files directly.

gatsby-config.js is used to configure Gatsby Plugins.

.prettierrc This is a configuration file for Prettier. Prettier is a tool to help keep the formatting of your code consistent.

Before we take a look inside the project folder, let’s run the development server. To do this, we will run one of the scripts that Gatsby provides. If you open the package.json file in the root and check the scripts property, you will see something like this:

Package.json contains the dependencies and scripts.

Package.json
Package.json

Our focus here should be on the develop script. This will start the development server and build our project locally.This script also comes with live reload so that changes are reflected in real time.

cd firstapp

gatsby develop

Gatsby Pages

Pages directory inside the src folder is used for setting up pages in the project.

The focus will be on the src/pages directory. we only have the index.js file in this folder.

With Gatsby, index.js will be the default homepage. To create a new page, all you have to do is to add a new file to the src/pages directory.

index.js can be accessed by loading localhost:8000

Let’s build an about us page.

Create a about.js file in the pages directory with the following react component.

Access the about page by loading http://localhost:8000/about

Let’s create blog and products pages.

Let’s build the 404 error page

Page Navigation in Gatsby

Using anchor tag for navigation would make the page to reload.hence to implement the single Page application mechanism we will import Link from Gatsby and use it to navigate between pages within the application.This has a whole lot of optimisation compared to the regular HTML <a> tag.

Link along with to prop is used for this purpose. Link tags allows the page to load instantly which provides a better user experience

<a href=””></a> is used to navigate to an external URL .

Gatsby Page Layout Component

Create Components folder within the src folder. We build all our react components in this folder.

Layout component contains Navbar and footer components.

Let’s create 3 files within the components folder namely Navbar.js , Footer.js and Layout.js

Once we have the Layout component ready , we include in any of the pages by importing it and making it as a parent div within the component. Here index.js as shown above uses the Layout component.

STYLING the Components in Gatsby

Using in-line css

We set the style to the elements by setting up style as shown in the line 6.

Setting the Global CSS

We create a layout.css file in components folder and import it in the layout.js

Managing the Data using GraphQL

GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data.

Gatsby, unlike other site generators, allows us to source data not only from the file system like Markdown but also from APIs, databases, CMSs like Contentful, WordPress, Drupal etc.

Let’s learn how to load data into Components using GraphQL.

We use GraphiQL IDE by loading http://localhost:8000/___graphql

Let’s begin by requesting our site Meta data (Information about our website)

We will add the siteMetadata in gatsby-config.js

Here’s the list of properties that are allowed to be configured in gatsby-config.js , setting up anything apart from these would lead to build failure.

  1. siteMetadata (object)
  2. plugins (array)
  3. flags (object)
  4. pathPrefix (string)
  5. polyfill (boolean)
  6. mapping (object)
  7. proxy (object)
  8. developMiddleware (function)

For detailed understanding of gatsby config API , Visit https://www.gatsbyjs.com/docs/reference/config-files/gatsby-config/

Note: Remember to Restart the server and refresh the IDE when ever changes are made to the gatsby-config.js

This panel makes it super easy to construct your queries by clicking through available fields instead of manually typing out these queries.

The query result is displayed in JSON format on the right side.

In GraphQL, you can perform three main types of operations — The query, mutation and subscription. But with Gatsby, we are only concern about the query operational type.

The query and the MyQuery (which is the operational name) as seen in the GraphiQL are optional. You can decide to omit them from your queries once you are sure that no other query will be on the page.

Now that we are getting the data we want, we will move the query into our Gatsby site and load these data.

We can use the explorer to select the properties we need and generate the query and Run to see the response.

Rendering the Data

We have Three options to render the Data

  1. StaticQuery
  2. PageQuery
  3. useStaticQuery (Hook)

Let’s begin Exploring each of these ways to export data

1. StaticQuery

In the IDE, Click on Code Exporter then choose StaticQuery from the dropdown and then copy the code.

Within components folder create a graphData folder and create a graphdata.js file in the Pages folder

Now within the Graphdata folder create a Header.js file paste the code that’s copied from the IDE.

Now. Let’s render the data in the graphdata page present in the pages folder by importing header component in grapghdata.js

2.Page Query

We cannot use PageQuery in components directory. We can only use pagequery in the components in Pages directory.We can setup StaticQuery in the pages.

copy the Page query code generated from the IDE. Create a page.js file in the pages directory folder and rename componentName to page within the copied code.

In the code, query is a constant which has the graphql query. The result of the query is data which is passed to the page component.

Upon loading localhost:8000/page , we see the result of the query being rendered on the page url.

3. useStaticQuery (Hook)

In the IDE, Click on Code Exporter then choose StaticQuery hook from the dropdown and then copy the code.

Let’s refactor the copied code, We store the result of the graphql query in the constant getData.

Within the Header component definition we define a define a object within needed key value pairs and assign it to the useStaticQuery hook which takes getData as argument. We can now render the values by using the keys.

Senior Engineer - Wavelabs ( www.wavelabs.ai )

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store