How to Build Your First Static Site with Gatsby

Thinking about getting on the JAMStack bandwagon? If your answer is Yes, then Gatsby, one of the hottest static site generators around, could be just what you’re looking for.

JAM stands for JavaScript, APIs, and Markup. In other words, when the dynamic parts of a site or app during the request/response cycle are taken care of by JavaScript in the client, all server-side processes take place using APIs accessed over HTTPS by JavaScript, and templated markup is prebuilt at deploy time often using a static site generator, that’s the JAMStack. It’s performant, inexpensive to scale and offers better security and a smooth developer experience.

Why Use a Static Site

The static site model doesn’t fit all kinds of projects, but when it does it has a number of advantages. Here are a few of them.

Speed

The time it takes a website to load in the browser as the request is made for the first time is an important factor for user experience. Users get impatient very quickly, and things can only get worse on slow connections. A lack of database calls and the content being pre-generated make static sites really fast-loading.

A static site is made of static files which can be easily served all over the world using Content Delivery Networks (CDN). This makes it possible to leverage the data center which is closer to the location from where the request is made.

Simplified Hosting

Hosting for static sites can be set up in a snap. Because there is no database or server-side code, special languages or frameworks to support, all the hosting has to do is to serve static files.

Better Security

Without server-side code or a database, there isn’t anything for hackers to hack. There’s no hassle keeping the server up-to-date with security fixes and patches. All this means a lot more peace of mind when it comes to the security of your static website.

Better Developer Experience

Setting up your static website with a hosting company like Netlify or Zeit is straightforward and, with continuous deployment, you just push your changes to your code repo of choice and they’re immediately reflected in the live version.

What Is Gatsby?

Gatsby is one of the most popular static site generators out there. It’s built with React, which means all React goodness is at your fingertips enabling you to take advantage of its power to build interactive components right into your static website. Gatsby is also built on top of GraphQL, so you can query data and display them on your static website any way you want.

Installing Gatsby and Creating Your Project

Gatsby is put together using Webpack, but you don’t need to worry about complicated set-up maneuvers — Gatsby CLI will take care of everything.

I assume you have Node.js installed locally, which means you also have npm available. You can use npm, the Node package manager, to install JS packages for your website. You can learn more about using npm here.

The first thing you need to do is install the Gatsby CLI. This is an npm package which lets you create a Gatsby site in a few seconds. In your terminal, write:

npm install --g gatsby-cli

With the Gasby CLI installed on your machine, you can go ahead and create your website. I’ll call it sitepoint-demo, but you’re free to call it whatever you like. In your terminal, type:

gatsby new sitepoint-demo

Once Gatsby CLI has installed all the necessary files and configured them appropriately, you’ll have a fully functioning Gatsby website ready for you to customize and build upon. To access it, move into the sitepoint-demo folder:

cd sitepoint-demo

and start the local server:

gatsby develop

Finally, open a window on http://localhost:8000 where you’ll find your shiny Gatsby site looking something like this:

Gatsby default template

To quickly get a website up and running, Gatsby takes advantage of several official starter boilerplates as well as starters offered by the strong community around it. The site you’ve just created uses Gatsby default starter, but you can find plenty more on the Gatsby website.

If you’d like to use a different starter from the default one, you need to specify its URL in the command line, following this pattern:

gatsby new [SITE_DIRECTORY_NAME] [URL_OF_STARTER_GITHUB_REPO]

For instance, let’s say you’d like a Material Design look and feel for your static site. The quickest way of creating it, is to use Gatsby Material Starter by typing the following command in your terminal:

gatsby new sitepoint-demo https://github.com/Vagr9K/gatsby-material-starter

Great! Now let’s take a look at the files inside your brand new Gatsby project.

A Tour Inside Your Gatsby Static Site

A good place to start is the /src/ directory. Here’s what you’ll find.

Pages Directory

The /src/pages/ directory contains your site’s pages. Each page is a React component. For instance, your site’s homepage code is located in /pages/index.js and looks like this:

    import  React  from  "react"
    import { Link } from  "gatsby"
    import  Layout  from  "../components/layout"
    import  Image  from  "../components/image"
    import  SEO  from  "../components/seo"

    const  IndexPage  =  ()  =>  (
    <Layout>
      <SEO  title="Home"  keywords={[`gatsby`, `application`, `react`]}  />
      <h1>Hi people</h1>
      <p>Welcome to your new Gatsby site.</p>
      <p>Now go build something great.</p>
      <div  style={{ maxWidth:  `300px`, marginBottom:  `1.45rem` }}>
        <Image  />
      </div>
      <Link  to="/page-2/">Go to page 2</Link>
    </Layout>
    )

    export  default  IndexPage

That’s the typical code for a React component, that is:

a self-contained pieces of code (usually written with JSX) that can accept input, and return React elements describing a section of UI. – Gatsby docs.

Components Directory

The /src/components/ directory is where you find general components for your website. The default starter comes with the following components: Header (header.js), Image (image.js), Layout (layout.js), and SEO (seo.js). You’re free to customize these components and add your own to the same directory.

Now you’re ready to start making changes to your new site and customize it to your taste.

How to Make Changes to Your Gatsby Site

Let’s have a go at modifying the message displayed on the Home page. Open pages/index.js in your code editor and replace the two paragraphs below the <h1> tag with this paragraph:

    <p>Welcome to my SitePoint Demo Site!</p>

Of course, you can add any text you want in-between the <p> tags.

As soon as you hit Save, your changes are displayed in the browser thanks to Gatsby’s hot reload feature.

Gatsby makes it easy to add new pages. For instance, let’s add an About page by creating a new file, about.js, inside the /pages/ directory and enter this content:

    import  React  from  "react"

    const  AboutPage  =  ()  => <h1>About Me</h1>

    export  default  AboutPage

The code above is a React stateless functional component which displays some text.

Save your work and navigate to https://localhost:8000/about and you should see the About Me <h1> title on your screen.

You can quickly link to your new About page from the Home page using the Gatsby Link component. To see how it works, open index.js in your code editor and locate this bit of code just before the </Layout> closing tag:

    <Link  to="/page-2/">Go to page 2</Link>

Next, replace the value of the to property with /about/ and the Go to page 2 text with About :

    <Link  to="/about/">About</Link>

Save your work and you should see your new link on the screen. Click on the About link and instantly you’re on the About page.

Gatsby uses the Link component for internal links. For external links, you should use the good old <a> tag, like you would on a regular vanilla HTML website.

Now, let’s experiment with your Gatsby site’s look and feel by changing a few styles.

Styling Your Gatsby Site

Gatsby offers a number of options for applying style rules to your static website.

Global Stylesheet

A familiar choice is to use a global .css file which contains rules that apply to the entire website. To get started, add a /styles/ directory inside the /src/ directory and add a global.css file to it: /src/styles/global.css . You’re free to choose any name you like both for the directory and the stylesheet file. Inside global.css, add the following CSS declaration, which is going to be applied to the entire website:

    body {
      background-color: yellow;
    }   

Now, save your work. Oops, nothing happens! Not yet, anyway. To make it work you need to take an extra step. Open gatsby-browser.js in your code editor and import the stylesheet you’ve just created:

    import  "./src/styles/global.css"

Finally, start your development server by typing gatsby develop in your terminal and there you have it: the background color on your website has turned into a bright yellow. Not ideal as a color choice, but it works!

Global Styles with a Shared Layout Component

Although adding a global stylesheet and importing it into gatsby-browser.js works just fine, the recommended way of adding global styles to your static Gasby website is by using a shared layout component. The Gatsby Default Starter comes with this component and its related stylesheet out of the box.

To see how it works, open layout.js and layout.css in your code editor (you’ll find both files inside the components/ directory).

At the top of layout.js, notice the import statement which makes available the CSS rules contained in layout.css to the shared Layout component and therefore to the entire website:

    import  "./layout.css"

In layout.css, locate the CSS declaration for the body element, it should be around line 199. This is what it looks like:

    body  {
      color:  hsla(0,  0%,  0%,  0.8);
      font-family:  georgia,  serif;
      font-weight:  normal;
      word-wrap:  break-word;
      font-kerning:  normal;
      -moz-font-feature-settings:  "kern",  "liga",  "clig",  "calt";
      -ms-font-feature-settings:  "kern",  "liga",  "clig",  "calt";
      -webkit-font-feature-settings:  "kern",  "liga",  "clig",  "calt";
      font-feature-settings:  "kern",  "liga",  "clig",  "calt";
    }

Now add a rule for the background color, something like this:

    background-color: yellow;

Save your work, and you should see your website’s background color turn once again into yellow.

Component-Scoped Styles: CSS Modules

A CSS Module is a CSS file in which all class names and animation names are scoped locally by default.

With CSS modules, your styles get applied only to a specific component, which helps keeping components self-contained and therefore easy to maintain and reuse.

CSS Modules comes bundled with Gatsby out of the box and the docs recommend this way of adding styles to Gatsby components and React components in general.

Follow these steps to add a fancy paragraph component to your About page.

Create the Fancy Paragraph Component

Inside the /components/ directory of your Gatsby Default Starter-based project, create a file and call it fancy-paragraph.js.

Open fancy-paragraph.js in your code editor and enter the following code:

    import  React  from  "react"
    import  fancyParagraphStyles  from  "./fancy-paragraph.module.css"

    const  FancyParagraph  =  (props)  => <p  className={fancyParagraphStyles.fancy}>{props.paragraphText}</p>

    export  default  FancyParagraph

This is a simple React functional component — nothing new except for the statement that imports the fancy-paragraph CSS module, which you haven’t created yet.

The component uses the styles contained in the fancy-paragraph module as a value inside the className property. As you can see, that value looks very much like a regular JavaScript object that uses .fancy, which is the name of the class, as the fancyParagraphStyles object’s property. You’ll write the styles for this class in your CSS module.

Create the Fancy Paragraph CSS Module

Inside /components/ create another file and call it fancy-paragraph.module.css. Open this file and style the .fancy class any way your fancy takes you, it’s just regular CSS. This is what mine looks like:

    .fancy  {
      font-size:  1.5rem;
      text-align:  center;
      line-height:  1.2;
      padding:  0.5rem;
      color: #fff;
      background-color:  rebeccapurple;
      font-weight:  800;
      font-style:  italic;
      text-transform:  uppercase;
    }

Now, you’re ready to use your Fancy Paragraph component with your fancy styles anywhere on your static Gatsby site.

Let’s add a fancy paragraph to your About page.

Add the Fancy Paragraph Component to the About Page

Start by adding these two import statements to your About page, just below the already existing React import:

    import  Layout  from  "../components/layout"
    import  FancyParagraph  from  "../components/fancy-paragraph"

The snippet above makes available the Gatsby Layout component, which you’re going to use in your About page, and the Fancy Paragraph component you’ve just created.

Next, modify your AboutPage functional component to look like this:

    const  AboutPage  =  ()  =>  (
    <Layout>
      <h1>About Me</h1>
      <FancyParagraph  paragraphText="Styled with CSS Modules." />
    </Layout>
    )

Your new component works just like any other React component, simply slap it on the page, in the exact location you want it to appear and you’re done. This particular component leverages React props to make the paragraph text more dynamic.

Save your work and navigate to the About page, where you should see your fancy paragraph in all its glory. Mine looks like this:

About page styled with CSS Modules

Mission accomplished!

Component-Scoped Styles: Inline Styles

An additional option for styling components is just to add inline CSS styles in the form of a JS object.

You can see this pattern in action in your Gatsby Default Starter-based project. For instance, open index.js in your editor and locate this code inside the IndexPage component:

    <div  style={{ maxWidth:  `300px`, marginBottom:  `1.45rem` }}>
      <Image  />
    </div>

Notice how CSS styles are applied to the <div> that contains the Image component: styles take the form of a JS object where CSS property names are the keys and CSS values are their corresponding values.

Also, notice how compound CSS property names remove the dash (-) symbol and use the camelCase convention instead, e.g., marginBottom , not the CSS margin-bottom.

How to Deploy Your Gatsby Site

There are companies that make it super quick and convenient to host static websites. Among the most popular are:

Let’s use Netlify to launch your brand new Gatsby website. Netlify provides:

An all-in-one workflow that combines global deployment, continuous integration, and automatic HTTPS.

It works great for hosting static websites.

First, you need to create a production build of your Gatsby project. To do so, enter the following command in your terminal:

gatsby build

Now you have a folder named public containing all the static files your website needs to run in the browser.

The next step consists of getting your Gatsby project into a repository like GitHub. Netlify supports GitHub, GitLab, or Bitbucket: each time you push changes to your code, Netlify runs a build with your chosen tool and deploys the results to its fast-loading CDN.

To get started just log in to Netlify, select New site from Git, choose your repository, enter your build command and the name of your public folder, then click Deploy site.

You can review the deployment process in detail in this video on the Netlify docs.

Congratulations, your Gatsby static website is live!

Next Steps and Resources

To really master Gatsby, head over to its website and check out the official tutorial and the docs.

Also, to get the most out of Gatsby, I recommend you get fluent with manipulating data using GraphQL. Here are a couple of great tutorials to get you started:

Finally, make sure you browse Gatsby Tutorials, a community-updated list of video, audio and written tuts to help you learn Gatsby inside out.

Sponsors

Replies

  1. I am a big fan of Gatsby. It is great if you are already a react dev and want to create your own blog because you don’t have to learn a lot more to be able to jump in and use it. I also use it to build out nice quick landing pages that can then be hosted on netlify.