Building a Gatsby Blog with 8base
Tags: 8base, react, graphql, gatsby
Published: 2019-08-02 17:24:06

---
title: Building a Gatsby Blog with 8base
published: true
description: How to build a static website using gatsby and 8base
tags: 8base, react, graphql, gatsby 
---

![final app screenshot](https://res.cloudinary.com/daintu6ky/image/upload/v1564761894/Building_a_Blog_with_Gatsby_and_an_8base_content_API_2x.png)

A static website contains Web pages with fixed content. Each page is simply an HTML file with fixed content that is displayed to the visitor every-time they visit your website.

Because static websites are not dynamic, they do not require any back-end programming or database. This reduced complexity makes it easier to deploy your website as no extra configuration is required once deployed to a hosting provider. With static websites, you can enjoy the power of the latest web technologies like React.js, Vue.js, Webpack, modern JavaScript, CSS and more.

One of the main advantage is that they ensure smooth user experiences, blazing fast website speed, improved security, hassle-free deployment, in-expensive, less time-consuming and maintenance costs. Technically, since there is no database it can not be hacked and there is no need to render a page for each request, which makes Web browsing faster.

Over time, numerous open-source static websites generators have become available: Gatsby, Jekyll, Hugo, etc... Most of the time, the content is managed through static (ideally Markdown) files or a content API. These technologies have aided in the building of both static websites and blogs and have started gaining as much traction as their older blogging platforms like WordPress, Blogger, Drupal and Joomla.

In this tutorial, we will build a blog using Gatsby for the frontend and 8base for the backend.


> N/B: To follow this tutorial, a basic understanding of React and Node.js is required. Please ensure that you have Node and npm/yarn installed before you begin.


## What is Gatsby?
> Gatsby is a free and open-source framework based on React that helps developers build blazing-fast websites and applications.

With Gatsby, you can get the best of both worlds by using data from one or many sources. You can get data directly into your pages using GraphQL with headless CMSs, SaaS services, APIs, databases, your file system, and more.

Every static website needs a source of content. When building websites with Gatsby, you access your data through GraphQL. GraphQL allows you to declaratively express your data needs. In this tutorial, we will access our content by setting up content API using 8base.


## What is 8base?

8base is a GraphQL backend that lets javascript developers quickly deliver enterprise applications using full-stack JavaScript. It is a front-end framework agnostic, therefore it enables developers to create customer-facing applications however they choose to.

We will use 8base as a backend database layer for our app. This is where we will store and read posts for our blog.

We’ll also be making use of some GraphQL queries in the project, so some familiarity with GraphQL will be helpful.


## Getting Started 

8base offers a wide array of features to help developers build performant applications at a faster and much easier rate. Using the 8base Console, you can build your backend using a simple GUI that allows you to do things like:


- Define data schemas: create tables/table relationships
- Set permission and authorization roles
- Organize multiple projects into *Workspaces*
- Design queries using the API explorer (based on GraphQL)
- Manage files

To get started using 8base, follow the steps listed below:


* Create an account on [8base](https://auth.8base.com/login?state=g6Fo2SBrb283dEtrOGU4bndGUTFGQUVyZWNwcFlrNzVFVWw5Z6N0aWTZIHByblBCMU84VWREN1ZXLVJvVFRkclpYUjE0ai01cDJOo2NpZNkgcUdIWlZ1NUN4WTVrbGl2bTI4T1BMam9wdnNZcDBiYUQ&client=qGHZVu5CxY5klivm28OPLjopvsYp0baD&protocol=oauth2&response_type=token%20id_token&redirect_uri=https%3A%2F%2Fapp.8base.com%2Fauth%2Fcallback&scope=openid%20email%20profile&mode=signUp&nonce=x0M6LCwpVoLZ3u1HqwPuY.Qi1.YSBj6M&auth0Client=eyJuYW1lIjoiYXV0aDAuanMiLCJ2ZXJzaW9uIjoiOS4xMS4xIn0%3D). You can start using 8base for free.

![](https://paper-attachments.dropbox.com/s_5BB0EC7B7AAFF1A955F6F8B32F4388FD3950022B58E5ECA06E42E5FDCC0E6873_1563912863085_Screenshot+2019-07-23+at+9.13.09+PM.png)


* After sign up is complete, click on the **Data Builder** button to navigate to the [Data](https://app.8base.com/data/?source=post_page---------------------------) menu and click on “New Table” to start building your backend.


![](https://paper-attachments.dropbox.com/s_5BB0EC7B7AAFF1A955F6F8B32F4388FD3950022B58E5ECA06E42E5FDCC0E6873_1563913216889_Screenshot+2019-07-23+at+9.18.31+PM.png)


* After your new table is loaded, you’ll be taken to the schema to begin defining fields. Let’s take a look around and note a couple of things. On the left, you’ll see there are `System Tables` and `Your Tables`. Every new 8base workspace automatically comes prepackaged with a number of built-in tables. These tables are used to handle things like Files, Settings, and Permissions and can all be accessed through the 8base GraphQL API.

* Go ahead and **create a table**  `Posts` that consists of the following fields:


    title: 
      type: Field type is Text. 
      description: This will store the title of our blog post.
    
    body: 
      type: Field type is Text.
      description: This field will hold the body of our blog post.

![](https://paper-attachments.dropbox.com/s_5BB0EC7B7AAFF1A955F6F8B32F4388FD3950022B58E5ECA06E42E5FDCC0E6873_1563913230041_Screenshot+2019-07-23+at+9.19.19+PM.png)



* We need some sample posts to work with, so let’s add some sample data. Next to the schema menu icon were we created our schema, click on the *Data* tab and add a sample *Post* record by setting a title and body.


![](https://paper-attachments.dropbox.com/s_5BB0EC7B7AAFF1A955F6F8B32F4388FD3950022B58E5ECA06E42E5FDCC0E6873_1564332977999_Screenshot+2019-07-28+at+5.55.38+PM.png)


* Next, **copy the API endpoint URL** (available on the bottom left) — this is single endpoint for communication between your frontend and your 8base backend.


![](https://paper-attachments.dropbox.com/s_5BB0EC7B7AAFF1A955F6F8B32F4388FD3950022B58E5ECA06E42E5FDCC0E6873_1563913382208_Screenshot+2019-07-23+at+9.21.58+PM.png)


* Finally, for the purpose of this tutorial we’re going to **allow open access to Guests** by default so that dealing with authentication is optional. To allow guest access to your new *Posts* table, navigate to `Settings > Roles > Guest` and check the appropriate boxes under *Posts* and *F**iles*. 

All unauthenticated users who access your API endpoint are assigned the role of *Guest* by default. We won’t cover authentication in this tutorial. You can see how authentication should be handled in more detail [here](https://docs.8base.com/docs/authentication?utm_source=scotchio&utm_medium=blog&utm_campaign=codebeast&source=post_page---------------------------).


![](https://paper-attachments.dropbox.com/s_5BB0EC7B7AAFF1A955F6F8B32F4388FD3950022B58E5ECA06E42E5FDCC0E6873_1563945802925_Screenshot+2019-07-24+at+6.22.06+AM.png)


In just a few simple steps, we’ve finished setting up a production ready CMS backend using 8base. Let’s start work on the frontend side of the application.


## Using Gatsby

To start using Gatsby, we must first install it using the Gatsby CLI. Create a new working directory and run the following in your terminal:


    npm install --global gatsby-cli  


## Generate a Gatsby project

In the folder you previously created, generate your brand new Gatsby blog:


    gatsby new blog  

This command will generate a new blog using the [gatsby default blog starter theme](https://github.com/gatsbyjs/gatsby-starter-default.git).


## Start in development mode

Enter your project's folder and start the server by running the following command in your browser terminal:


    gatsby develop

Your Gatsby website would be available at this address: [http://localhost:8000](http://localhost:8000/)


![](https://paper-attachments.dropbox.com/s_5BB0EC7B7AAFF1A955F6F8B32F4388FD3950022B58E5ECA06E42E5FDCC0E6873_1563914873651_Screenshot+2019-07-23+at+9.47.25+PM.png)



## Connecting Our 8base backend  

To connect Gatsby to a new source of data, you can either use an [existing source plugin](https://www.gatsbyjs.org/plugins/) or [develop a new source plugin](https://www.gatsbyjs.org/docs/create-source-plugin). At the time of writing 8base doesn’t have a source plugin so we will write our configuration manually.

To connect our 8base backend we will make use of some Apollo GraphQL packages. To install them, run the following command in your terminal:


    npm install --save apollo-boost react-apollo apollo-link-http apollo-cache-inmemory graphql-tag

Next, we will create an `8base.config.js` file in the root of our project to hold all our configurations. Create the file and add the following code to it:

```javascript
     // 8base.config.js
    import { ApolloClient } from 'apollo-boost'
    import { ApolloProvider } from "react-apollo";
    import { createHttpLink } from 'apollo-link-http'
    import { InMemoryCache } from 'apollo-cache-inmemory'
    
    const ENDPOINT = 'YOUR-8BASE-ENDPOINT';
    
    const httpLink = createHttpLink({uri: ENDPOINT,});
    
    const client = new ApolloClient({
      link: httpLink,
      cache: new InMemoryCache()
    })
    
    export { client }
```


Next, we need to wrap our entire application layout with Apollo provider. Once that is done , we will be  *able to connect to and query 8Base from our components**.*

Open **layout.js** in the **src** directory ****and update it with the following code:

```javascript
    // src/layout.js
    
    import React from "react"
    import PropTypes from "prop-types"
    import { ApolloProvider } from 'react-apollo'
    import { client } from "../../eightBase-config.js";
    import "./layout.css"
    
    const Layout = ({ children }) => (
      <ApolloProvider client={client}>
        <main>
          {children}
        </main>
      </ApolloProvider>
    )
    
    Layout.propTypes = {
      children: PropTypes.node.isRequired,
    }
    
    export default Layout
```

Now, we need to write queries that would fetch all our posts from 8base. First, create a folder called **queries** inside the **src** folder, then create an **index file** and add the following to it**:**

```javascript
    // src/queries/index.js
    
    import gql from 'graphql-tag';
    
    const POSTS_QUERY = gql`
      query {
        postsList{
              items{
                id,
                title,
                body,
                createdAt
              }
           }
      }
    `;
    
    export { POSTS_QUERY }
```

Here, we’ve written a query to get all our posts from 8base.

To display all our posts we need to run the query. For that, let’s create a **posts.js** file ****component in the **src/components** folder with the following code:


```javascript
    // src/components/posts.js
    import React, { Component } from 'react'
    import { Query } from 'react-apollo'
    import { POSTS_QUERY } from "../queries/index";
    import { Link } from "gatsby";
    import './posts.css';
    
    export default class Posts extends Component {
    
      render() {
        return (
          <Query query={POSTS_QUERY}>
            {({ loading, error, data }) => {
              if (loading) return <h1>Fetching</h1>
              if (error)   return <h1>Error</h1>
              const posts = data.postsList.items
              return (
                    <div>
                      <div className="header">8thBlog</div>
                      {posts.map((post, index) => {
                          return (
                            <div key={index} className="main">
                                  <div className="card-body">
                                    <h2>
                                      <Link to="#" className="links">{post.title}</Link>
                                      <span className="created">Created At: {post.createdAt}</span>
                                    </h2>
                                    <p className="card-text">{post.body}</p>
                                  </div>
                            </div>
                          )
                      })}
                    </div>
                  )
              }}
            </Query>
        )}
    }
```

This code runs the query and returns it in the component. To see it on our page, we need to update our **src/pages/index** file which is the main page that is displayed when Gatsby is launched. Open up the page and add the following to it:

```javascript
    // src/pages/index.js
    
    import React from "react"
    import Layout from "../components/layout"
    import Posts from '../components/Posts';
    
    const IndexPage = () => (
      <Layout>
        <Posts />
      </Layout>
    )
    
    export default IndexPage
```

Next, create a `posts.css` file in the src/components and add the following code to it:

```css
    // src/components/posts.css
    .header {
        width: 100%;
        height: 70px;
        background-color: #036ffc;
        padding: 10px;
        text-align: center;
        font-size: 24px;
        margin-bottom: 20px;
        font-weight: bold;
    }
    
    .main {
        margin: 0 auto;
        width: 600px;
        padding: 15px;
    }
    
    .created {
      font-size: 12px;
      margin: 5px 0px 0px 5px;
      font-style: italic;
      display: block;
    }
    
    .links {
      text-decoration: none;
    }
```


To see the changes, restart your server run `gatsby develop` in your terminal, then visit http://localhost:8000 in a browser and you should see the following screen:


![](https://paper-attachments.dropbox.com/s_5BB0EC7B7AAFF1A955F6F8B32F4388FD3950022B58E5ECA06E42E5FDCC0E6873_1564331983784_Screenshot+2019-07-28+at+5.37.50+PM.png)



## Conclusion

Throughout the creation of our blog we’ve explored how to use 8base to get a functioning backend in minutes, we’ve also seen how to setup Gatsby and write queries to fetch data from the 8base GraphQL API. 8base as a platform is relatively easy to navigate and offers an intuitive user interface. You can also visit their official [documentation](https://docs.8base.com/?source=post_page---------------------------) to learn more about the how it works. 

Also, the source code of this tutorial’s blog application can be found [here](https://github.com/paulayuk/gatsby-8base).