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.
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.
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:
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:
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.
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 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.
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.
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: {} } } }
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.
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!
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowExplore use cases for using npm vs. npx such as long-term dependency management or temporary tasks and running packages on the fly.
Validating and auditing AI-generated code reduces code errors and ensures that code is compliant.
Build a real-time image background remover in Vue using Transformers.js and WebGPU for client-side processing with privacy and efficiency.
Optimize search parameter handling in React and Next.js with nuqs for SEO-friendly, shareable URLs and a better user experience.