đź“ť Building a static blog using Gatsby and Strapi

Written by strapi | Published 2018/01/18
Tech Story Tags: javascript | api | cms | gatsbyjs

TLDRvia the TL;DR App

A static website contains Web pages with fixed content. Technically, it is a simple list of HTML files, which displays the same information to every visitor. Unlike dynamic websites, they do not require any back-end programming or database. Publishing a static website is easy: the files are uploaded on a simple Web server or storage provider. The two main advantages of static websites are security and speed: there is no database so it can not be hacked and there is no need to render a page for each request, which makes Web browsing faster.

To make their creation easier, numerous open-source static websites generators are available: Jekyll, Hugo, Hexo, etc. Most of the time, the content is managed through static (ideally Markdown) files or a Content API. Then, the generator requests the content, injects it in templates defined by the developer and generates a bunch of HTML files.

Progressive Web Apps (PWA) are web applications, highly based on JavaScript, and are reliable, fast and engaging. Since they make web browsing much faster and offer a better user experience, PWA have become the default way to build Web interfaces. Thus, many amazing front-end frameworks appeared over the last couple years: Angular, Vue and more recently, React.

Gatsby: when static websites meet Progressive Web Apps

Static websites and PWA both have strong advantages which make us crave for a way to use them both in the same project! Luckily, we have tools that bridge the gap between them and the one we recently heard of is definitely Gatsby. So, we decided to give you a complete example of how to get started with Gatsby. A static website needs a source of content: in this example we will deliver it using an API built with Strapi.

What is Gatsby?

Gatsby is a blazing-fast website framework for React. It allows developers to build React based websites within minutes. Whether you want to develop a blog or a corporate website, Gatsby will fill your needs.

Because it is based on React, the website pages are never reloaded which makes the generated website super fast. A large set of plugins is available to let developers save time and get data from any source (Markdown files, CMS, etc.). Gatsby is strongly based on the “node” interface, which is the center of Gatsby’s data system.

Created by Kyle Mathews, the project has been officially released in July 2017and is already used by tens of companies.

What is Strapi?

Strapi is the most advanced Node.js Headless Content Management System.

Thanks to its extensible plugin system, it provides a large set of built-in features: Admin Panel, Authentication & Permissions management, Content Management, API Generator, etc.

Unlike others CMSs, Strapi is 100% open-source, which means:

  • Strapi is completely free.
  • You can host it on your own servers, so you own the data.
  • It is entirely customisable and extensible, thanks to the plugin system.

API Setup

To make the magic happen, let’s create a Strapi API and add some content.

Create a Strapi project

Install Strapi

Requirements: please make sure Node 8 (or higher) and MongoDB are installed and running on your machine.

Install Strapi using npm:

$ npm i strapi@alpha -g

Note: Strapi v3 is still an alpha version, but it will be fine for this tutorial.

Generate a Strapi project

Create a directory named gatsby-strapi-tutorial:

$ mkdir gatsby-strapi-tutorial

Scaffold your API inside it through a single command line:

$ cd gatsby-strapi-tutorial$ strapi new api

Start the server

Enter inside your project’s folder:

$ cd api

Launch the Node.js server:

$ strapi start

Starting now, you should be able to visit the admin panel of your project: http://localhost:1337/admin.

Create your first User

Add your first user from the registration page.

Create a Content Type

Strapi APIs are based on a data structure called Content Types (equivalent of models in frameworks and Content Types in Wordpress).

Create a Content Type named article with four fields:

  • title (type string)
  • content (type text)
  • image (type media)
  • author (type relation, many article to one user)

Insert some entries

Add some articles in the database. To do so, follow these instructions:

  1. Visit the articles list page.
  2. Click on Add New Article.
  3. Insert values, link to an author and submit the form.
  4. Create two other articles.

Allow access

For security reasons, API access is, by default, restricted. To allow access, visit the Auth and Permissions section for Guest role, select the Article - findaction and save. At this point, you should be able to request the list of articles.

The author API access is also restricted. Authorize anonymous access by selecting the find (in "Users & Permissions" section) action and saving the form.

Static website development

Great job, our API is ready! We can start developing the static website.

Install Gatsby

First, install Gatsby CLI:

$ npm install --global gatsby-cli

Generate a Gatsby project

In the folder gatsby-strapi-tutorial that you previously created, generate your brand new blog:

$ gatsby new blog

Start in development mode

Enter in your project’s folder:

$ cd blog

Start the server:

$ gatsby develop

At this point, you should already be able to get access to your Gatsby website at this address: http://localhost:8000.

Install the Strapi source plugin

When you manage a static website, your data can come from different sources: Markdown files, CSV files, a WordPress website (using the JSON REST API plugin), etc.

Gatsby understands this pretty well. So its creators decided to build a specific and independent layer: the data layer. This entire system is strongly powered by GraphQL.

To connect Gatsby to a new source of data, you have to develop a new source plugin. Fortunately, several source plugins already exist, so on of them should fill your needs.

In this example, we are using Strapi. Obviously, we are going to need a source plugin for Strapi APIs. Good news: we built it for you!

Let’s install it:

$ npm install --save gatsby-source-strapi

This plugin need some configurations. Replace the content of gatsby-config.jswith:

Path: _gatsby-config.js_

Then, restart the server to let Gatsby consider these updates.

Articles list

First, we want to display the list of articles. To do so, add the following content in the existing home page file:

Path: _src/pages/index.js_

What are we doing here?

At the end of the file, we export pageQuery, a GraphQL query which requests the entire list of articles. As you can see, we require only the id, title and contentfields, thanks to the precise GraphQL query language.

Then, we pass the { data } destructured object as parameter of IndexPage and loop on its allStrapiArticles object to display the data.

Tip: generate your GraphQL query in seconds!

Gatsby includes a useful GraphiQL interface. It makes GraphQL queries development way easier and intuitive. Take look at it and try to create some queries.

Adding images

To add images, we will need to import Img from package gatsby-image installed by default. Replace the content of src/pages/index.js with the following :

Path: src/pages/index.js

Article view

Our website now starts looking like a blog which is a good thing. However, an important part is still missing: the article’s details page.

Let’s create the template, containing a specific GraphQL request and defining the content displayed:

Path: _src/templates/article.js_

That looks fine, but at this point, Gatsby does not know when this template should be displayed. Each article needs a specific URL. So, we are going to inform Gatsby about the new URLs we need thanks to the [createPage](https://www.gatsbyjs.org/docs/creating-and-modifying-pages) function.

First, we are going to code a new function called makeRequest to execute the GraphQL request. Then, we export a function named createPages in which we get the list of articles and create a page for each of them. Here is the result:

Path: _gatsby-node.js_

Restart the Gatsby server.

From now on, you should be able to visit the detail page by clicking on URLs displayed on the homepage.

Author view

Articles are written by authors. They deserve a dedicated page.

The processes for creating author views and article pages are very similar. First, we create the template:

Path: _src/templates/user.js_

Second, we update the gatsby-node.js file to create the URLs:

Path: _gatsby-node.js_

Finally, restart the server and visit the author page from the article view’s links.

Conclusion

Congrats! You’ve successfully built a super fast and easy-to-maintain blog!

Since the content is managed by Strapi, the authors can write article through a nice UI and developers only have to rebuilt the Gatsby blog in order to update the content.

Where to go next?

Feel free to continue this project to discover both Gatsby and Strapi advantages. Here are some features you can add: list of authors, article’s categories, and comment system with the Strapi API or Disqus. You can also create other kind of websites (e-commerce shop, corporate website, etc.).

When your project is achieved, you will probably want to deploy it. The static website generated by Gatsby can easily be published on storage providers: Netlify, S3/Cloudfront, GitHub pages, GitLab pages, Heroku, etc. The Strapi API is nothing else than a simple Node.js API, so it can be hosted on Heroku or any Linux instance that has Node.js installed.

The code source of this tutorial is available on GitHub. To see it live, clone the repository, run npm run setup, start the Strapi server (cd api && strapi start) and the Gatsby server (cd blog && npm run develop).

We hope you enjoyed this tutorial. Feel free to comment on it, share it, and let us know how you create sites built with React and manage their content.


Published by HackerNoon on 2018/01/18