Advanced Rendering Strategies (Beyond SSG)
8 min read
Advanced Rendering Strategies (Beyond SSG)
Hey there, code adventurer! 🤠 So you've mastered the art of Static Site Generation (SSG) with Gatsby. Your sites are faster than a caffeinated cheetah, super secure, and deployed with the grace of a gazelle. But what happens when your project's needs grow beyond what a purely static site can offer? Fear not, for this guide will be your trusty map through the exciting landscapes of advanced rendering in Gatsby. We'll explore what to do when SSG hits its limits and how to wield the powers of Deferred Static Generation (DSG) and Server-Side Rendering (SSR).
1. Understanding the Limits of Static Site Generation (SSG)
Definition: Static Site Generation is the process of building all your website's pages at build time. This means when you deploy your site, all the HTML, CSS, and JavaScript are already pre-built and ready to be served to your users instantly from a Content Delivery Network (CDN).
The Problem: Imagine you run a massive e-commerce store with a million products. If you use traditional SSG, Gatsby will try to build a separate HTML page for every single one of those million products during the build process.
🔍 What happens?
- Insanely Long Build Times: Your build process could take hours, or even days! This is a huge bottleneck, especially if you need to update your site frequently. It’s like trying to print a million-page book every time you find a single typo.
- Wasted Resources: You're building pages for products that maybe only a handful of people will ever look at. This is a lot of work for very little reward.
- Content Freshness: If product information changes (like a price drop or a new review), you have to trigger a full site rebuild to show those updates. This isn't ideal for content that needs to be fresh and dynamic.
So, while SSG is fantastic for blogs, portfolios, and marketing sites where content doesn't change every second, it starts to creak and groan under the weight of very large or very dynamic sites. This is where our other strategies come into play.
2. Deferred Static Generation (DSG): Building Pages on Demand
DSG is the clever middle ground between building everything upfront (SSG) and building everything on every request (SSR).
Definition: Deferred Static Generation allows you to defer the building of certain pages until the first time a user requests them. Once a page is built, it's cached on the CDN and served statically to every subsequent user, just like a regular SSG page.
How it Solves the Problem: Instead of building all one million of your product pages at build time, you can tell Gatsby, "Hey, let's just build the most popular 1,000 pages for now. For the other 999,000, wait until someone actually tries to visit one, then build it and save it for later."
This is a game-changer! 🚀
- Dramatically Faster Builds: Your initial build time plummets because you're only building a small subset of pages.
- Efficient Resource Use: You're not wasting time and energy building pages that nobody might ever see.
- Still Great Performance: After the very first user takes a tiny performance hit (while the page is being built on the server), every other user gets that super-fast, static experience.
Implementing DSG in Gatsby
Let's get our hands dirty. To use DSG, you need to tell Gatsby which pages to defer. You do this in your gatsby-node.js file.
Imagine we're creating pages for blog posts. Here’s how you would defer the creation of some of them:
// gatsby-node.js
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions;
const result = await graphql(`
query {
allMarkdownRemark {
nodes {
id
frontmatter {
slug
}
}
}
}
`);
result.data.allMarkdownRemark.nodes.forEach(node => {
createPage({
path: `/blog/${node.frontmatter.slug}`,
component: require.resolve('./src/templates/blog-post.js'),
context: {
id: node.id,
},
// This is the magic part! ✨
defer: true,
});
});
};By simply adding defer: true to your createPage call, you're telling Gatsby to hold off on building that page until it's requested.
🧠 Fun Fact: DSG is like a self-stocking pantry. You don't buy every single ingredient in the supermarket at once. You buy the essentials, and then when you decide to bake a specific cake for the first time, you go get those specific ingredients. From then on, you have them ready for the next time.
3. Implementing Server-Side Rendering (SSR) in Gatsby
Now, what if your content is so dynamic that you need a fresh version on every single request? Think of a user's profile page, a dashboard with real-time data, or search results. Caching a static version wouldn't work because the content is personalized or changes constantly. This is where Server-Side Rendering shines.
Definition: Server-Side Rendering (SSR) generates the HTML for a page on the server every time a user requests it. The browser receives a fully rendered page, just like with SSG, but this page is freshly baked for each visitor.
How it Solves the Problem: For highly dynamic content, SSR ensures that every user sees the most up-to-date information. If a user updates their profile, the changes are reflected instantly on the next page load because the server is re-generating the page from scratch.
Implementing SSR in Gatsby
To create an SSR page in Gatsby, the convention is to place your page component inside a src/pages directory and name the file with a special syntax: [fileName].js. For example, a user profile page might be src/pages/user/[id].js.
The key to SSR is the getServerData function. You export this function from your page component, and Gatsby will run it on the server for every request to that page.
Here's an example of a server-rendered page that fetches user-specific data:
// src/pages/account.js
import React from 'react';
const AccountPage = ({ serverData }) => {
// The data fetched by getServerData is passed as the serverData prop
const { user } = serverData;
return (
<main>
<h1>Hello, {user.name}!</h1>
<p>Your email is: {user.email}</p>
</main>
);
};
export default AccountPage;
// This function runs on the server for every request to this page
export async function getServerData(context) {
try {
// In a real app, you'd fetch this from a secure API
// The 'context' object contains request information like headers and params
const userId = getUserIdFromRequest(context.headers);
const res = await fetch(`https://api.example.com/users/${userId}`);
if (!res.ok) {
throw new Error(`Response failed`);
}
const userData = await res.json();
return {
props: {
user: userData,
},
};
} catch (error) {
return {
status: 500,
headers: {},
props: {},
};
}
}In this example, getServerData is called before the page is rendered. It fetches fresh data and passes it as serverData props to your page component. This ensures the user always sees their current information.
4. Architectural Choices: When to Use SSG vs DSG vs SSR
Alright, you now have three powerful tools in your Gatsby belt. But which one should you use? The answer, as always, is: it depends. Let's break it down into a simple decision-making framework.
| Rendering Method | When to Use It | Pros | Cons |
|---|---|---|---|
| Static Site Generation (SSG) | Your content doesn't change frequently. Examples: Blogs, portfolios, marketing sites, documentation. | 🚀 Blazing fast, 🛡️ Highly secure, 💸 Cheap to host | 🐌 Long build times for large sites, stale content requires rebuild. |
| Deferred Static Generation (DSG) | You have a very large site, but most pages are not frequently visited. Examples: Large e-commerce sites, big documentation portals. | ⚡️ Fast build times, great performance after first load. | 🤔 First visitor to a deferred page experiences a slight delay. |
| Server-Side Rendering (SSR) | Your page content is highly dynamic or personalized. Examples: User dashboards, search results, shopping carts. | ✨ Always up-to-date content, great for SEO. | 🐢 Slower than SSG/DSG, requires a server, more complex to manage. |
A Real-World Scenario: An Online Store
Let's simulate how you might use all three on an e-commerce site:
- SSG for your main marketing pages: The homepage, about us, contact page. These don't change often and need to be super fast for first impressions.
- DSG for your individual product pages: You have thousands of products. You can build the top 100 most popular ones with SSG and
deferthe rest. This keeps your build times manageable while still providing a great experience for most users. - SSR for the user's shopping cart and account pages: This content is unique to each user and changes with every action they take. SSR is perfect for ensuring the cart and user details are always 100% current.
By mixing and matching these rendering strategies, you can create a highly optimized site that is fast, scalable, and provides a fantastic user experience. You get the best of all worlds! 🌍
📚 References for Extra Reading
- Gatsby Rendering Options: https://www.gatsbyjs.com/docs/rendering-options/
- Deferred Static Generation (DSG): https://www.gatsbyjs.com/docs/how-to/rendering-options/using-deferred-static-generation/
- Server-Side Rendering (SSR): https://www.gatsbyjs.com/docs/how-to/rendering-options/using-server-side-rendering/
getServerDataAPI: https://www.gatsbyjs.com/docs/reference/config-files/gatsby-node/#getServerDatacreatePagesAPI: https://www.gatsbyjs.com/docs/reference/config-files/actions/#createPage
Challenge
You are tasked with optimizing the build and rendering process for a large-scale e-commerce website using Gatsby. The site has thousands of product pages, standard marketing pages, and a personalized user account section. Your goal is to correctly apply Static Site Generation (SSG), Deferred Static Generation (DSG), and Server-Side Rendering (SSR) based on the specific requirements for each part of the site.
Requirements:
In
gatsby-node.js:- You will receive a mock array of
allProducts. The first 10 products in this array are considered 'featured' products. - Iterate over the
allProductsarray to create a page for each product at the path/products/{product.slug}. - For the 10 'featured' products, the pages should be generated at build time using SSG.
- For all other products (non-featured), the pages should be generated on the first user request using DSG.
- You will receive a mock array of
In
src/pages/account.js:- This page must display user-specific, real-time data that is fetched for every single page visit.
- Implement SSR for this page by exporting a function that fetches mock user data. The function should return the data under a
propskey.
Expected result
gatsby-node.js
The createPages export in gatsby-node.js should be updated to correctly implement the conditional logic for DSG. The createPage action inside the forEach loop must include a defer property. This property should be set to true only if product.isFeatured is false, and false or omitted otherwise.
// ... inside gatsby-node.js
allProducts.forEach(product => {
createPage({
path: `/products/${product.slug}`,
component: require.resolve(`./src/templates/product-page.js`),
context: { id: product.id },
defer: !product.isFeatured,
});
});
// ...src/pages/account.js
The src/pages/account.js file should export an async function called getServerData. This function should simulate a data fetch and return an object with a props key. The value of props should be the data passed to the page component.
// ... inside src/pages/account.js
export async function getServerData(context) {
// In a real app, you would fetch data from an API based on user credentials
const userData = {
user: {
name: 'Jane Doe',
lastLogin: new Date().toISOString(),
},
};
return {
props: userData,
};
}
// ...