Deborah Emeni I'm a software developer and technical writer who specializes in Node.js and JavaScript.

What’s new in Gatsby v4

5 min read 1460

What's new in Gatsby v4

Gatsby is best known as a React-based, GraphQL-powered static site generator that has a rich data plugin system for management systems, APIs, and databases. Gatsby also has several plugins that can extend its functionality beyond a regular static site generator.

The Gatsby v4.0 framework, released in September 2021, offers great improvements for both the developer and user experience, as well as a foray into the world of server-side rendering, a first for the framework. We’ll cover all of the new features in this article, including:

Let’s review these below, covering a few of them with relevant examples.

Introducing parallel query running

In previous Gatsby versions, a unified data layer was used to simplify working with content from multiple content management systems. Gatsby v2.0 and v3.0 were introduced to allow developers to launch faster websites; they enabled new features that only built pages or processed images when the development server requested them.

In version 4.0, Gatsby has cut the build time down even further with the introduction of parallel query running, which is typically the largest part of the build process. Parallel query running is the first step towards a fully decoupled future, meaning builds are faster.

Gatsby has historically been single-threaded; regardless of the number of cores available on a machine, Gatsby leverages only a single thread to perform tasks. However, parallel query running leverages multiple cores, meaning slower builds will now be done in parallel on a greater number of more powerful machines — which speeds up builds by as much as 40 percent.

Improved content management with Preview UI

The new Preview UI offers an improved content visualization and editing experience that helps content editors stay informed and be very effective. As an editor, you can see changes you make on your CMS with one click in real-time.

Here’s a small demo on the Preview UI:

Preview UI demo

When developers go headless with Gatsby in their websites, regardless of their choice of CMS, their content editors aren’t left stranded when they make changes. As a content editor, if you are using Contentful as an example CMS, you can make changes in the editor. When you click the open preview button, it will display a building a new preview button, just at the left corner:

We made a custom demo for .
No really. Click here to check it out.

Building a new preview button

Deferred static generation

Deferred static generation (DSG) is a technique for speeding up build times by deferring the generation of non-critical pages and instead, generating only what is needed in real-time.

Only the critical portions of your Gatsby site are generated at build time, while the rest are generated and made available to the user when they request it. This triggers builds when users access the live pages instead of generating everything up front.

DSG can drive down build time up to 10x, especially for larger webpages that have content that can be generated in the background.

For things like older sites or certain content types that aren’t often accessed, you can leverage the benefits of the static web generator where you’re waiting for the builds to complete.

To enable DSG, you can follow the instructions in the official documentation.

Hosting with Gatsby Cloud

Gatsby Cloud is a new platform that uses a modern developer toolset and workflow for a better Gatsby experience.

Gatsby uses incremental builds to reduce build time or deployments. When you make a change to your site, Gatsby calculates the time from the change made to the change being live to your users around the world with a CDN.

Also, Gatsby hosting was unveiled as Gatsby shifted to a more dynamic territory to meet the needs of teams. It solves the problem of publishing updates to a site that has now been shifted to deploy-times.

In addition to this feature on Gatsby Cloud, the gatsby-plugin-gatsby-cloud has been updated. This plugin helps you control headers and redirect your projects on Gatsby Cloud.

Gatsby Shopify source plugin and starter

Gatsby now offers its own Shopify storefront starter to further convince content creators to choose Gatsby for their ecommerce website’s frontend.

While it’s still in beta, the new starter lets you get started with Gatsby much more quickly than before, and provides a wide range of easily customizable options for your build, most of which are built with CSS Modules.

Server-side rendering

One of the biggest changes in this version is Gatsby’s new support for server-side rendering (SSR). Server-side rendering is done on a pre-user and pre-request basis. If you want to scale real-time data requirements or fetch details on a test based on server side conditions, SSR will enable you to build your website.

These techniques and rendering models are new functions for Gatsby. Collectively, these tools and APIs will drive down build times by as much as 10x.

Achieving SSR with Gatsby

To illustrate SSR, we’ll utilize the getServerMethod() by using it to fetch data from the animechan API by Rocktim Saikia, a simple API that returns random anime quotes, the names of the source anime, and the names of the characters who speak those quotes. Then, we will dynamically render the data from getServerData() method in our page.

If you don’t have an existing Gatsby site, you can follow this guide to get started.

Here is our sample request:

fetch('https://animechan.vercel.app/api/random')
.then(response => response.json())
.then(quote => console.log(quote))

And here is our sample response:

{
anime: 'Tengen Toppa Gurren Lagann',
character: 'Kamina',
quote: 'Don\'t believe in the you that believes in me and don\'t believe in the me that believes in you. Believe in the you that believes in yourself.'
}

Create a simple React component and hard-code the anime name, quote, and character. We will render this dynamically shortly:

import React from "react”;
const AnimeQ = () => (
<main>
<h1>Anime Quote Of The Day</h1>
<h3>Anime</h3>
<p>Anime Quotes</p>
<p>Anime Character</p>
</mani>
export default AnimeQ;

Request data from within getServerData(). The async getServerData() is a method that instructs Gatsby to choose the SSR rendering option for us.

This data has to be returned as an object with just one property, props, whose value is the API response:

export async function getServerData() {
try {
const res = await fetch(https://animechan.vercel.app/api/random)
if (!res.ok) throw new Error(`Couldn’t get response!`)

return {
  props: await res.json(),
}
} catch (err) {
return {
headers: {
status: 500,
},
      props: {}
    }
  }
}

Whenever a user visits the page, the API is called and the response returned is available as serverData to the page, which we will accept as a prop. Let’s render this data dynamically and take out the hard-coded values:

const AnimeQ = ({serverData}) => (
<h1>Anime Quote Of The Day</h1>
<h3>{serverData.message.anime}</h3>
<p>{serverData.message.quote}</p>
<p>{serverData.message.character}</p>

)
export default AnimeQ;
export async function getServerData() {
try {
const res = await fetch(https://animechan.vercel.app/api/random)
if (!res.ok) throw new Error(`Couldn’t get response!`)

return {
  props: await res.json(),
}
} catch (err) {
 return {
    headers: {
   status: 500,
},
           props: {}
     }
  }
}

Improved documentation and tutorial experiences

Finally, if any of these new features intrigues you, Gatsby has provided a new tutorial and overall documentation experience to help you get started quickly. The tutorial shows you how to build a blog and use the latest APIs available for Gatsby ≥v3.

Conclusion

Gatsby is always evolving, and its main aim has always been to enable developers to build sites with fast page loads, fast image loading, and fast data prefetching. With the release of Gatsby v4, there has been a noticeable increase in speed due to the implementation of DSG — and, with their plan to introduce a new, open source version of Gatsby every two weeks, you’ll notice some real improvements to the overall Gatsby user experience as calculated by the build up speed if you’re updating your version of Gatsby with each, incremental point release.

Now that updates will happen more often, we’ll get to see more of Gatsby that comes with newer features enabling developers and editors get the best experience. What are you waiting for? Upgrade to Gatsby version 4.0!

: Full visibility into your web apps

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

.
Deborah Emeni I'm a software developer and technical writer who specializes in Node.js and JavaScript.

Leave a Reply