Headless CMS: Gatsby JS with WordPress

Table of contents

The website user experience should always be best if you want your website to provide enhanced performance. There’s no better way to reduce the complexity of your website than using Headless CMS WordPress. Gatsby can do that for you as by integrating into your WordPress website, you can provide enhanced performance and high security to your website. Gatsby is one of the speediest front-end frameworks to use with headless WordPress for many reasons. Here, we will learn what Gatsby is and how to integrate it with your WordPress site.

Its common knowledge that WordPress covers roughly one-third of the top 1 million websites in the world with over 50% market share in Content Management Systems. As recently as 2016, WordPress decided to introduce a REST API to provide other applications with improved access to content in the WordPress database. Resultantly, provides developers with the ability to leverage WordPress as a headless CMS.

This inevitably implied that engineers would no longer be limited to employing WordPress’s conventional presentation layer (frontend), but could now exploit any frontend application to deliver their data. In light of this, the majority of this blog will explore the relationship between WordPress and Gatsby.js in regard to Headless CMS effectuation.

A Brief History of CMS

As we take a step back to understand the Headless CMS revolution, I think it’s noteworthy to recap the history of content management systems (CMS). Traditionally, in the early ’90s, static webpages were the main way to execute websites where a webmaster would directly edit HTML files and upload them to a server via FTP. Eventually, in the mid-’90s, web technology started to evolve and content became more dynamic, leading to the emergence of the first monolithic content management systems.

Essentially, a Monolithic CMS is a software application that includes everything required to edit and publish content on the web. The first such systems were limited to enterprises such as EpiServer, however, later open-source variations appeared like WordPress, Drupal, and Joomla.  The rest is history as WordPress gained the most market share over time.

However, later during the smartphone revolution, mobile devices started to affect how web content was consumed and delivered. This was a challenge to traditional monolithic CMSs designed to deliver web content for laptops and desktops.

To mitigate this, responsive design was born which resulted in website layouts that were adaptive to screen size. Consequently, this also allowed decoupling content management from the display layer. This is where our Headless CMSs come in.

Headless CMSs

As mentioned before, a Headless CMS is one without a presentation layer. As a result, content is delivered via an API (RESTful or GraphQL) to separate frontend application that then presents it. The API makes content available to any channel and device using a variety of tools and programming languages with a higher level of security and scalability.

Essentially, the CMS is decoupled from frontend concerns, which in turn frees developers to build rich experiences for end-users, using the best technology available. A “headless” or “decoupled” mode is currently supported by most CMSs, which paved the way for Gatsby sites.

So, to leverage a headless CMS, you’ll have to build your site or application first, then use the CMS’s API to plug your content in.

The WordPress Headless CMS execution

With respect to the chronology of events shared above, we have seen how WordPress ended up effectuating a Headless CMS. WordPress Contains an API (Application Programming Interface) that allows you to extend it with plugins (essentially as an ‘application framework’). In particular, this is achieved via the REST API as we shall later.

However, one of the key concepts of the WordPress API is hooks. Basically, hooks allow plugins to change WordPress core functionality. Practically, Hooks work in a way that when a certain event in WordPress occurs (for instance, page load, or post-edit), WordPress calls a certain hook to run the function.

Specifically, hooks are split into ‘Actions’ and ‘Filters’. Actions can be leveraged to run certain PHP functions in certain events, though the functions don’t need to return anything. While Filters can be utilized to run functions that WordPress passes data through during certain events with these functions taking data in as a parameter and returning a modified version of the data.

WordPress and the REST API

The Representational state transfer (REST) is based on HTTP protocol and provides uniform interface semantics to create, read, update and delete data (CRUD).

Generally, the REST API execution in WordPress enables developers to access data in a WordPress database remotely by sending and receiving JSON (JavaScript Object Notation) objects. Consequently, this allows developers to create, read, update and delete WordPress data from other applications that are not engineered with WordPress. For instance, JavaScript Web Applications or native mobile apps.

However, as we get deeper into understanding the Headless WordPress CMS relationship with REST APIs and Gatsby, we’ll need to note a few fundamental concepts of the WordPress API:

  • Routes and Endpoints: Routes are paths you can access via HTTP call while an endpoint is an HTTP method (such as get, post, put or delete) mapped to that route.
  • Request: When you initiate an HTTP request to a registered REST route, WordPress will automatically create a request object. Data that is specified in the request will determine what answer you will get back.
  • Response: A Response object is a data you receive back when you make a request. It can comprise requested data or error messages.
  • Schema: A schema refers to the data structure in the endpoint. Each endpoint can have slightly or significantly different structure of data it can return. Accordingly, a schema will determine all possible properties an endpoint can return and all the possible parameters it can receive.
  • Controller Classes: Controller Classes enable developers to manage and register endpoints and routes, whilst also allowing them to handle requests, utilize schema and generate responses.

The React ‘Framework’

As we now get into the meat of the Gatsby.js and WordPress relationship, for more context, we have to decipher this technological landscape from more historical basics. React is key to this story as it is the fastest-growing JavaScript frontend library/framework. Made famous by Facebook (its core developers), other large websites utilize React for their frontends such as Airbnb, Netflix, Dropbox, BBC, PayPal, Reddit, Salesforce, Squarespace, and Tesla.

Consequently, since React is a library in practice (as it still lacks notable features of a full-fledged framework), this means that other ‘frameworks’ can be engineered on top of it. Resultantly, one of these is Gatsby.js.

Introducing Gatsby

According to its parent website, Gatsby.js is a free and open-source JavaScript framework based on React that helps developers build fast websites and apps. In principle, Gatsby.js generates static HTML pages from applications for initial load and then proceeds as a single-page React application (SPA).

Gatsby.js Attributes

Under those circumstances, Gatsby exploits Progressive Web App (PWA) principles to fetch only the elements required first and then loads the rest of the application in a background later. Furthermore, to ensure only the data required is loaded Gatsby leverages the GraphQL query language (also by Facebook) to load the data from the source. It also maintains exceptional image optimization.

All these capabilities merged give developers the necessary tools to create the fastest possible websites and web apps as it only loads critical HTML, CSS, data, and JavaScript. So, once a page is loaded Gatsby prefetches resources for linked pages, and thus navigating the site feels pretty fast.

Also, since pages are generated at compilation, before online placement, you don’t need powerful PHP servers anymore and can serve static files (HTML, JS, and CSS, directly from bucket storage). Additionally, since Gatsby is powered by React, you’ll be able to nicely structure everything with components. This modular aspect allows developers to easily reuse components.

Other significant out-of-the-box Gatsby features include:

  • Static site generator
  • Offline access
  • Prefetching linked pages
  • Page caching
  • No extraneous code fetching
  • Export as code
  • Hot reload content
  • Hot reload code
  • Componentization
  • One-way data binding
  • Declarative API data queries (GraphQL)
  • Declarative UI
  • Progressive image loading
  • Responsive image loading
  • Inlining of the critical CSS
  • Font self-hosting
  • Serverless
  • Asset pipelines
  • CSS Extensions (SaSS)
  • Advanced JavaScript syntax
  • React component ecosystem

Gatsby Plugins

Essentially, Gatsby plugins are fundamentally Node.js packages that use the Gatsby API. These plugins can add data sources, transform data to other formats and add third-party services. Though Gatsby.org maintains a plugin library that includes many already-made plugins made by either the core Gatsby team or third parties.  Ideally, to install a plugin for a Gatsby project, developers employ the node package manager (NPM) on their UNIX terminal and run the command npm install.

How GraphQL Comes relates to Gatsby.

GraphQL revolves around the idea that you can describe to the API exactly the data you precisely want, and you will receive exactly that. As a result, it’s more efficient than REST. To this end, Gatsby employs Webpack and GraphQL. More importantly, with GraphQL as the query language, everything is defined on the side of the client executing the query, with the client oblivious to the under-workings of the application.

This unique implementation enables developers to connect any data source to Gatsby. For example, blog posts can come from Markdown files, Google sheets, or even another WordPress website. Hence, providing enhanced flexibility with content delivery.

Gatsby-WordPress Mechanism (Source Plugins)

As we further unpack this relationship, we need to understand source plugins. Source plugins are special plugins that work within Gatsby’s data system. As the name already implies, they source data from different locations, either local or remote. Consequently, the data is then turned into what Gatsby refers to as nodes and node fields. Basically, node fields represent a single piece of data inside one node, and ultimately, these nodes can be accessed via a GraphQL query.

In the same breadth, through source plugins, Gatsby supports dozens of headless CMS options, availing engineering and content teams the comfort and familiarity of its preferred admin interface with the improved developer experience and performance benefits of using Gatsby, GraphQL, and React to build a frontend.

The ‘Gatsby-source-WordPress’ plugin is built and maintained by the Gatsby core team and pulls data either from self-hosted WordPress sites or WordPress.com. It also entails OAuth authentication to Word-Press.com API, and also allows developers to query responsive images.

Essentially, this plugin supports all entities on the WordPress REST API such as posts, pages, tags, categories, media, types, users, statuses, taxonomies, site metadata, and custom post types. Furthermore, Advanced Custom Fields (ACF) entities and Polylang and WPML language information is also supported, in addition to other post meta registered to the REST API.

So, with this plugin, developers can choose which routes to fetch, though it fetches all endpoints of wpjson by default. So, developers can fetch data from WordPress with GraphQL employing the above mechanism.

In practice, the ‘Gatsby-source-WordPress’ tool provides a slug for all posts and other entities. And thus, all an engineer needs to do is create a page by calling the ‘createPage’ function. This is executed in the Gatsby-node.js file, ordinarily by first running a query for the data source and then calling ‘create pages’ for each found node, then setting a template file to be used as a component.

CI/CD and Application Release Automation.

When implementing a headless WordPress CMS with Gatsby, how deployment is performed is highly critical. Typically, such executions require the deployment of an application to be automated utilising Application Release Automation (ARA).

Generally, ARA entails primary functions:

  • Deployment of data, application code, and artifacts.
  • Deployment of specific configurations for each environment
  • Process workflow design for automating tasks, and deployment steps.
  • Lastly, environment modeling and/or provisioning binaries

Since Gatsby produces static sites, it is imperative to set up an ARA pipeline so that when content is updated in WordPress, it can correspondingly be updated in the Gatsby site. Typically, continuous deployment is triggered only when code changes, however, for this instance, it is desirable to trigger it when data changes. So, for this, we recommend using Netlify as it possesses remarkable in-built continuous deployment capabilities, and is user-friendly to set up.

Querying from WordPress using GraphQL and gatsby-source-WordPress

As an illustration, gatsby-source-WordPress works in a way that it will first fetch everything on your endpoint using REST. Then it will generate an internal GraphQl API based on that data. Subsequently, it then will go through your queries and gather the data from that internal GraphQL API. So, basically, your build only ends up with the data you asked for and nothing else.

Advantages of Headless WordPress development with Gatsby.js

Since we have touched on Headless WordPress development with Gatsby, we can now break down the pros of this sort of technical approach. This should essentially guide your decision on whether to adopt Gatsby or not!

  • The first benefit is the ability to have a static, prerendered site. This is the most efficient way to render a webpage, and since Gatsby employs GraphQL to execute the minimum amount of data needed, this provides some extra efficiency for the time after the initial load.
  • Improved SEO visibility: Static pages are easy for search engines to read as everything is prerendered and indexable. This is a positive, in contrast to other headless mechanisms where rendering pages with JavaScript is an issue concerning search engine optimization (SEO).
  • The relatively quick speed of development: In comparison to other headless approaches, Gatsby has one unified, easy-to-understand way of fetching data regardless of the source. This makes development rather simplified as you can focus on your actual site and let Gatsby do the majority of the heavy lifting.
  • Cheaper Hosting: You can host your Gatsby application anywhere since it’s just serving static files, thus cutting on hosting expenses. Additionally, since WordPress is only called during the build process, and never during the user session, it can be hosted on an affordable hosting solution too.
  • Enhanced Security: Generally speaking, static site generators are tremendously safe since there is no direct connection to a database, dependencies, user data, or other sensitive information.
  • Plugin free: From a non-developer’s perspective, WordPress is quite easy to operate because of the available plugins. However, this restricts the implementation of custom functionalities. Unfortunately, also too many plugins can slow down a site as it becomes heavy and harder to render. A Gatsby execution essentially circumvents all these bottlenecks.

More facets that can motivate you to consider Gatsby with WordPress:

  • Easy to manage WordPress admin panel.
  • Ready to use user login system and authorization.
  • With Gatsby and Gutenberg editor, you can build a drag-drop Gatsby site builder.

Disadvantages of Headless WordPress development with Gatsby.js

  • Update limitations: When content changes from scratch, it sets restrictions on how frequently your site can update. Additionally, it can take up to 10 minutes to run Gatsby build if your site contains a lot of data, which can be an issue for sites that update frequently.
  • Regular Updates Hustles: Also, since Gatsby is a static site generator, it cannot just be “edited”, as even small text changes will require a new deployment. So, if you have a page that requires many dynamic daily content changes, this can become time-consuming and a hustle.
  • Delays:  You typically have to wait several minutes to see changes in your content as they go live.
  • Lack of Previews: Unlike in traditional WordPress applications, you don’t have any kind of preview in Gatsby. Sadly, this has been the biggest issue content creators have found with Gatsby. You will need to compile everything, probably with Gitlab CI/CD pipelines that compile the website and put everything online.
  • Steep Learning curve: Generally, if you desire to work with Gatsby and WordPress at the same time, you need to be relatively familiar with both PHP and JavaScript languages. Since Gatsby merges React and GraphQL, this can be a steep learning curve for many.

Final Thoughts.

In conclusion, thanks to its performance and business advantages, more companies are implementing Gatsby as a part of their tech stack. Though it is important to remember that by amalgamating Gatsby with WordPress, WP becomes backend only, which implies that you’ll lose some of its functionalities and abilities.

As a result, WordPress developers experience Gatsby as a great tool with its modern performance, scalability, security, and development speed benefits. All this while allowing them to retain the familiar content creation user interface offered by WordPress.

However, before initiating this technology, one should always consider their project specifications and objectives. For instance, if the emphasis is on scalability, performance, speed of development, and long lifecycle, Gatsby will do. However, if the emphasis is to have enhanced flexibility and tools for non-programmer content creators with content updated on a second or minute basis, then you can consider an alternate approach.

Bhargav Bhanderi
Bhargav Bhanderi
Director - Web & Cloud Technologies

    Have a Project in Mind, Let's Discuss

    India
    A-404, Ratnaakar Nine Square,
    Opp Keshavbaug party plot,
    Vastrapur, Ahmedabad (380015), Gujarat.
    +91 79 40086120
    United States
    4059 Ida Ln,
    Vestavia Hills,
    Birmingham AL 35243,
    United States.
    +1(205) 417-7500
    Hong Kong
    Unit 06, 25/F,
    Metroplaza Tower II,
    223 Hing Fong Road,
    Kwai Chung, Hong Kong.
    +852 92014949