Knowledge Hub
Gatsby
Written by Thom Krupa
Last update: 6/7/2024
Feature | Gatsby | |
---|---|---|
Written in | JavaScript | |
Template Language The syntax or language used to define the layout and structure of web pages. | JSX | |
Based on JS framework | React | |
Built-in module bundler | webpack | |
Static pages (SSG) | ||
Dynamic pages (SSR) | ||
Developer Experience | ||
TypeScript support | ||
Serverless Functions (API) Small pieces of code that run on-demand without managing servers, typically used for API endpoints. | ||
Focus on plugin system | ||
Themes ecosystem | ||
Hot reloading The ability to instantly see changes in the browser without refreshing the page when developing. | ||
Code Splitting The ability of splitting code into smaller chunks to load them only when needed, improving performance. | ||
Content Preview Allows content editors to see live changes to draft content in a staging environment before it goes live. | ||
Builit-in Optimizations | ||
Third-party Script Optimization Optimizing external scripts (like analytics or ads) to improve the performance and loading speed of your website. | ||
Image Optimization | ||
An option to disable runtime JS For certain use cases, like static HTML + CSS websites where interactivity isn't needed, shipping JavaScript is unnecessary. | Community example | |
Critical CSS Extraction Extracting only the CSS needed for the initial page load to improve performance. | ||
Starters or examples with common use cases | ||
Data fetching Methods to fetch data from APIs or other sources, either at build time or runtime. | ||
10+ Headless CMS examples | ||
Authentication | ||
Adding search | ||
Ecommerce | ||
Security | ||
Regular security audits by external researchers | ||
Environment Variables Variables used to configure applications based on different environments (development, production). | ||
Content Security Policy (CSP) | Community example |
GatsbyJS was born in 2015 as a simple static site generator. During the last 5 years, it has become the most popular solution in the market. Gatsby helped Jamstack grow to what it is now.
In 2019 Gatsby, Inc. secured $15M in Series A funding and built its first commercial product - Gatsby Cloud, CI platform that focuses on fast incremental builds. I'll talk about this a bit later. Let's start with the SSG overview.
One of the most opinionated things in Gatsby is data fetching. Gatsby creates an internal GraphQL API. It's a kind of middleware between the content sources and the frontend template.
You can connect Gatsby with every popular Headless CMS. A large collection of plugins makes it easy. You can mesh sources in a single GraphQL query. Everything becomes one, big graph.
You need to learn GraphQL and Gatsby API to enjoy the mesh concept. For simple static websites, it might be too much. Working with GraphQL can be painful, errors sometimes are weird. Debugging is hard. Some people like it, others don't.
If you ask me, GraphQL API is a good way to unify and standardize the way we build products at agencies like ours. No matter what CMS we pick, the way we generate pages and fetch data is similar.
For instance, take a look at how to fetch products from Shopify and content from Contentful:
const HomePage = ({ data }) => {
return (
<div>
All products:
{data.allContentfulProducts.edges.map(({ node }) => (
<div key={node.id}>
<h2>{node.title}</h2>
</div>
))}
</div>
)
}
export const query = graphql`
query HomePageQuery {
allContentfulProducts(filter: { node_locale: { eq: "en-US" } }) {
edges {
node {
id
slug
title
}
}
}
allShopifyProduct {
edges {
node {
id
title
productType
vendor
variants {
id
title
price
}
}
}
}
}
`
export default HomePage
You can fetch data from everywhere. Headless CMS, local filesystem, external GraphQL or REST API, Google Spreadsheet, Airtable, and so on. You can write your own to create a custom integration with your backend.
GraphQL queries execute only during the build. If you change something in the CMS, you need to rebuild the project. You can still fetch data on the client like in any other React app. For example, using SWR or a simple , but it won't be pre-rendered.
An example file structure shown below:
├── gatsby-browser.js
├── gatsby-config.js
├── gatsby-node.js
├── gatsby-ssr.js
├── package-lock.json
├── package.json
├── src
│ ├── html.js
│ └── pages
│ ├── 404.js
│ ├── about.js
│ ├── blog.js
│ ├── contact.js
│ └── index.js
└── static
└── logo.png
The first four files you have access to Gatsby API. In other words, you can modify what Gatsby does under the hood. Add plugins, generate pages from API, adjust SSR, manage what is happening on init render in the browser, and so on. Explore full API's capabilities reading the official docs.
Over the years the community of Gatsby devs has created thousands of themes, plugins, and starters. Gatsby has the biggest ecosystem in the Jamstack space. The last time I checked the plugins library, there were more than 2400 ready to install packages.
You may like plugins or not. But there is a great possibility that someone already had the same issue as you and published a solution for it.
Among the most popular plugins are , , and . There are a bunch of plugins that improve the performance of pages like . We've talked about Gatsby plugins made to tackle performance issues previously. Check it out.
A large ecosystem enhances the developer experience. This basically means boring tasks like generating a sitemap or adding a content security policy already have a solution.
To install Gatsby globally on your computer, run the command:
npm install -g gatsby-cli
The fastest way to get started with Gatsby is to use one of many starters available.
To create a project from the starter, pick one from the gallery, copy its Github URL, and run:
gatsby new my-website https://github.com/gatsbyjs/gatsby-starter-default
To start the Gatsby project locally, run:
cd gatsby-site && gatsby develop
Your dev environment will be available on .
You can deploy Gatsby anywhere. The only command that needs to be executed is:
gatsby build
The folder contains all static files ready to be published.
Everything works fines when your project contains a small amount of GraphQL queries and images. For a larger set of images - think a few hundreds - the build tends to be very slow. In some cases, CI/CD tool can fail with time out error.
If you want to improve the build time, the easiest solution is to switch to Gatsby Cloud. It is designed to support fast Incremental Build and has better cache management.
Gatsby Cloud handles the building part, but to deliver the website to users, you need to host it somewhere. It's easy to connect projects with any of the popular hosting providers. Gatsby integrates with Netlify, Vercel, Fastly, Google Storage, Azure, Firebase, and AWS S3. Pick the one that matches your existing infrastructure best.
Gatsby.js is a good fit if you use many data sources and want to use one internal API to rule them all. Gatsby, like Next, is based on React. It's easy to create interactive components, but it comes with JS cost. Client-side routing optimizes perceived performance, especially on high-end devices.
It's not the lightest static site generator because it requires loading a bunch of JavaScript. It might be tough to achieve a perfect Lighthouse score, but sometimes that's not the point. You can create a very fast website that will be very fast and pleasant to use for your audience.