Introducing GatsbyJS

Overview

There is a new modern web development architecture in town called the JAMstack. It is based on client-side JavaScript, reusable APIs, and prebuilt markup. GatsbyJS embraces this philosophy by creating blazing-fast and secure apps and sites using modern technologies like React and GraphQL. In this article, we are going to build a complete modern static blog site with Gatsby using React components and GraphQL and a methodology in line with the JAMstack, all thanks to the power of GatsbyJS. We will be using GatsbyJS version 2 to build a fast static blog that you can host very cheaply, even for free if you wish, all with unprecedented speed and very secure in nature. Static sites also have the added advantage of being great with regards to search engine optimization (SEO), so that is also a plus. Some of the major topics that will be covered include how to get started creating static sites with GatsbyJS; creating reusable React components like headers, buttons, and footers; working with Gatsby’s plugins and extensibility points; using GraphQL to query for data; and deploying a static site to a modern web hosting provider. This article assumes you are familiar with basic JavaScript, HTML, CSS concepts, basic knowledge of the command-line interface and running basic commands.

The JAMstack Architecture

Before we start to learn about GatsbyJS, I think it’s important to understand about this new concept called the JAMstack. What is JAMstack? JAM stands for JavaScript, API, and Markup. The term was coined by Mathias Biilmann, cofounder of Netlify . As per the definition on the official JAMstack website, JAMstack is a modern web development architecture based on client-side JavaScript, reusable APIs, and prebuilt Markup. In other words, a site that adheres to JAMstack only uses static content like HTML, images, CSS, JavaScript, and calls external APIs over HTTP that typically exist in the form of REST endpoints. These APIs can be created by you or by an external organization that provides a particular service. The client logic lives in the static JavaScript files, and the business logic comes from these external endpoints. In more traditional applications, the rendering of a site happens on the server at runtime, while in a static site, the rendering happens at build time in your computer while building the application or in a build server if you wish to do so.

So what are the advantages of using the JAMstack? For starters, JAMstack offers better performance compared to server-side rendered applications, especially if you host your static site in a CDN, you can get subsecond access times in this way. Static sites offer better security because they offer a reduced attack surface compared to dynamic sites. Removing system components, like a database from the equation, can have significant advantages, including eliminating SQL injection attacks. Moving he business logic away from your app also decreases the risk of an attack. Now it’s the responsibility of API creators to secure that part of the application. Static sites are cheap to host and scale. You can serve your site in more places faster. Finally, if your goal is good SEO performance, static sites can also dramatically improve the discoverability of your site.

So to recap, when is a site built with JAMstack in mind? A site is built with JAMstack in mind when all site components are static; you create site assets like HTML pages at build time instead of runtime; when it uses JavaScript to add dynamic programming on the client side, it could be any front-end framework like Angular, Vue, or React, for example, or a library such as jQuery or even plain old vanilla JavaScript; uses markup that is HTML, but also CSS, images, or any other type of static content; and finally, it calls external APIs that perform the heavy lifting when business logic functionality or database access is required.

Now let’s see when a site does not adhere to JAMstack. If you build a site with a server-side render framework like a content management system (CMS), such as WordPress, for instance, your site does not adhere to the JAMstack framework. The same applies to a web-application created with more established frameworks like C#, and .NET, Java, and Spring, and Node, and Express just to name a few. These frameworks render your application in the server, hence not adhering to JAMstack either. A less intuitive example is a single-page application created with a front-end framework like Angular, Vue, or React that is isomorphic in nature that is a sort of a blended server-side rendered application and a single-page application.

So what does Gatsby and JAMstack have in common then? Well, Gatsby adheres to all tenants in the JAMstack, and does it magnificently using the best technologies and workflows that work in tandem to provide a great user experience for developers. Now that we have a clear understanding of JAMstack and its advantages, it’s time to explore Gatsby in more detail. We will do that next.

What is GatsbyJS?

GatsbyJS is a modern front-end framework for creating static sites and applications. It’s been built upon modern technologies such as React, GraphQL, and Webpack, amongst other front-end technologies. One thing that makes Gatsby unique is that you  don’t have to know React or GraphQL to start working with Gatsby. You can learn Gatsby as a way to introduce yourself to the world of React, GraphQL, and modern front-end development in general. Its creators have taken out the guesswork of configuring a modern workflow to build sites based on these technologies; therefore, creating sites with Gatsby is fun, productive, and easy, and the results are great. I mentioned React and GraphQL, but what are these and what do they do?

React is a JavaScript library for building modern user interfaces. It was created by Facebook to help their development teams in creating modern and responsive applications. Along with Vue and Angular, it’s the defacto framework to build modern apps today. With React, the focus is on building small components that you can reuse throughout the application.

GraphQL is also a technology created by Facebook and is a query language that allows you to query for data in a declarative way by describing the data you intend to get from a data source. It lets you specify the data your application needs and gets that data in the format you initially requested. We will be using GraphQL for querying data when building blog site.

The goal of Gatsby is to create static sites and applications comprised of HTML, CSS, JavaScript, and other static content. The difference between Gatsby and other static site generators is the way Gatsby accomplishes this goal. Think about the different types of data. It could be Markdown files, an external database, or an API, a JSON file, or even a text file. Gatsby lets you query with this data with GraphQL in the format you need. For example, you can query data from a Markdown file sitting in your local drive that you intend to use as the content for our blog post. GraphQL grabs the file content, its file name, the blog post title, and the creation date and uses this information to create a static HTML file ready to be uploaded on the server.

Okay, another example. Let’s say you want to create a page with a list of popular products that your company sells. This data changes once every three months or so and resides in a database. The traditional approach was to create a server-side rendered application that connects to a database, generally, through a endpoint exposing this data and then generate the page on the fly at runtime with the desired information. With Gatsby, we take a different approach. We call the endpoint with GraphQL, fetch the data you need, and then create a static HTML page with the required data. The information is only queried once and served from the server as a prebuilt static HTML file. Another cool thing about Gatsby is its rich plugin ecosystem which brings a lot of functionality to Gatsby.

Alright, we went over React, GraphQL, and the merits and benefits of static sites and using Gatsby. Gatsby is the way to go when you want to build a site that is fun to develop, uses a modern workflow and future-proof technologies, adheres to the tenants of JAMstack, is fast, secure, inexpensive to host, and has excellent SEO capabilities.

Gatsby goes beyond creating static sites. React and GraphQL are used by thousands of companies and developers to create sophisticated web applications. Since Gatsby uses React, we can use Gatsby to develop sophisticated web applications as well.

Lastly, I want to go over browser support for Gatsby briefly. Gatsby currently supports the same browsers as the current stable version of React, that is Internet Explorer 9 and above, as well as the most recent versions of other popular browsers. They are also known as ever-green browsers, in other words, browsers that self-update. Next, let’s go over the installation process of GatsbyJS.

What is the Web Animations API?

In the context of web apps, animation is nothing more than the visualization of change over a specified duration. This visualization of change is very important because when done right we can use this to dramatically increase the user experience of an app and make our apps feel more refined and well designed.

At the highest level, the Web Animations API is a standardized JavaScript API which is baked into browsers that allows developers to animate DOM elements. CSS was always been the most performant way to animate on the web because the CSS animations engine can run animations on the GPU instead of the CPU allowing us to achieve smooth 60 fps animations. The Web Animations API finally allows us to write animation logic using JavaScript and opens up the browsers animation engine allowing us to run these animations on the GPU. As well as performant animations there are host of other benefits the Web Animations API provides us. Because it is a JavaScript API we can easily create dynamic animations by altering durations, easing methods and other variables; something which is very hard to do in CSS. The API provides very flexible playback control which allows us to Pause, Rewind, Skip and even change the rate of playback and more. The API is Promise based so it is really easy to chain multiple animations or run other logic when the animation completes. And because the Web Animations API is a browser feature there are no external dependencies to manage or maintain. Today most JavaScript libraries take a component based approach. Whether that’s using Angular, React, VueJS or just native web components the Web Animations API fits in with this architecture because the JavaScript used to create this animations can be embedded into the components easily without any dependencies. These are great benefits provided by the Web Animations API which we can use to harness the power of the GPU to create silky smooth animations that are dynamic and flexible.

Exploring the WP-API

Checking the API index

The WP-API provides us with an index of all available routes and their endpoints. To get to that index, type in, for e.g., http://localhost/wp-json/wp/v2 in Postman. This is a first level route. All the other routes start with this, and then continue onwards.

Exploring Common Routes

API Index – GET /wp-json/wp/v2/ => This gives us a list of all the available routes and, within each of the routes, you will get a list of all the available endpoints and within the endpoints, you get a list of all the available arguments.

Post index (10 latest posts) – GET /wp-json/wp/v2/posts

Post index (all available posts) – GET /wp-json/wp/v2/posts?per_page=0

Single post based on ID – GET /wp-json/wp/v2/posts/{post-ID}

Page index (10 latest pages) – GET /wp-json/wp/v2/pages

Single page based on ID – GET /wp-json/wp/v2/pages/{page-ID}

Category index (10 first categories, alphabetically) – GET /wp-json/wp/v2/terms/category

Category index (all available categories) – GET /wp-json/wp/v2/terms/category?per_page=0

Single category based on ID – GET /wp-json/wp/v2/terms/category/{cat-ID}

Posts in category based on category slug – GET (…)/posts?filter[category_name]={slug}

Posts in category based on category ID – GET (…)/posts?filter[cat]={cat-ID}

Tag index (10 first tags, alphabetically) – GET /wp-json/wp/v2/terms/tag

Tag index (all available tags) – GET /wp-json/wp/v2/terms/tag?per_page=0

Single tag based on ID – GET /wp-json/wp/v2/terms/tag/{tag-ID}

Posts in tag based on tag name (slug) – GET (…)/posts?filter[tag]={slug}

Posts in tag based on tag ID – GET (…)/posts?filter[tag_id]={tag-ID}

User index (10 most recent) – GET /wp-json/wp/v2/users

Current logged in user – GET /wp-json/wp/v2/users/me

Single user based on ID – GET /wp-json/wp/v2/users/{user-ID}

Comments index (10 most recent) – GET /wp-json/wp/v2/comments

10 latest comments on specific post based on post ID – GET /wp-json/wp/v2/comments?post={post-ID}

All comments on specific post based on post ID – GET /wp-json/wp/v2/comments?post={post-ID}&per_page=0

WordPress REST API (WP-API)

What is the WP-API?

The WP-API is a RESTful API that can be accessed through simple HTTP requests to access the site data in JSON format. The WP-API is a new way of accessing the data WordPress provides without having to go through a theme, or a RSS feed, or XML-RPC. Using WP-API we can now Create, Read, Update and Delete (CRUD) content in the WordPress database without interacting with WordPress directly. Getting the data from a WordPress site using the API is as simple as submitting a standard HTTP request or URL. Once you have that data you can use any application or programming language to do whatever you want with it. So we can build WordPress sites using PHP or we can build them using JavaScript or Ruby or Objective-C or whatever we want. The WP-API gives us direct access to the data and allows us to do whatever we want with it. The WP-API also allows us to access and edit the data in the database without going through WordPress Admin. However, this is only possible if you have the right security credentials so your data is not at risk.

What are RESTful APIs and JSON?

REST is an acronym for REpresentational State Transfer and describes the software architecture of the web. A RESTful application is typically one that uses standard HTTP verbs like GET, POST, PUT and DELETE to retrieve and send data from and to a remote server. RESTful applications use resources – essentially URIs to interface with external systems such as a remote server and use the 4 HTTP verbs to perform operations on the server.

API is an acronym for Application Programming Interface and is a set of routines, protocols and tools for building applications and interfaces.

RESTful API is an application programming interface that uses resource URIs to perform operations on a remote server through HTTP verbs. We can send a URI to the server, and get pure data back. In the WP-API, data comes back as JSON.

JSON is an acronym for JavaScript Object Notation and is an open standard format used to transmit data objects in the form of attribute-value pairs for further processing. JSON is typically used for asynchronous communication between browsers and servers, the kind of communication performed by RESTful APIs, and is favored over XML because it’s cleaner and easier to work with.

In Summary, The WP-API is a RESTful API for WordPress that returns data objects in the JSON format when provided with a route and an endpoint.

Understanding routes and endpoints.

Interacting with the WP-API is done through accessing routes and endpoints. The WP-API has a wide variety of routes and endpoints.

An Endpoint is a function available through the API in the form of HTTP verbs GET, POST, PUT, and DELETE. An endpoint performs a specific function by taking one or more parameters and returning the resulting data to the client.

A Route is the “name” we use to access the available endpoints. In simple terms, the route is the URL, and the endpoint is the action performed on the URL.

For Example,

GET wp/v2/posts/1234 => Retrieves the data from post 1234 as an object

PUT wp/v2/posts/1234 => Updates the database entry for the object with the ID 1234

DELETE wp/v2/posts/1234 => Deletes the database entry for the object with the ID 1234

In the above example, GET, PUT and DELETE are the endpoints whereas wp/v2/posts/1234 is the route.

Information about the WP-API can be found at

  1. WP REST API v2 Documentation
  2. WP REST API – a JSON-based REST API for WordPress Project on GitHub
  3. WordPress REST API (Version 2) Plugin