Creating Dynamic Websites with Gatsby SSR and Builder.io Integration

In this post, we’ll start by setting up a Gatsby Starter app and integrate Builder.io to test the Server-Side Rendering capabilities.

Gatsby is a powerful and widely-used static site generator that empowers developers to swiftly create and deploy websites. One of its notable features is Server-Side Rendering (SSR), enabling the creation of dynamic websites by fetching data from a server. In this tutorial, we’ll explore how to build a blog post using Gatsby SSR and seamlessly integrate Builder.io.

What is Server-Side Rendering?

Server-Side Rendering (SSR) is a web development technique where the server generates the fully-rendered HTML content of a web page, including dynamic data, before delivering it to the user’s browser. This approach significantly improves initial load times, enhances SEO, and ensures content is visible without solely relying on client-side JavaScript.

Prerequisites

Before we dive in, make sure you have the following installed:

  • Node.js
  • Gatsby CLI (Optional, required only if you want to create a new project)
  • Builder.io Public Key

Step 1: Create a Gatsby Project

You have two options:

  1. Clone/download the Gatsby Starter from the GitHub repository.
  2. Create a new Gatsby project using the Gatsby CLI:
gatsby new my-gatsby-ssr-builder-demo

This command will create a new Gatsby project in a folder called my-gatsby-ssr-builder-demo.

Step 2: Install Builder.io

Next, install the Builder.io React library by running the following command in your terminal:

npm install @builder.io/react

Step 3: Replace the src/pages/index.js File

Replace the contents of src/pages/index.js with the following code:

import * as React from "react"
import { BuilderComponent, builder } from '@builder.io/react'

builder.init(process.env.BUILDER_PUBLIC_KEY);

const Page = ({ serverData }) => {
    return (
        <div>
            <div>Hello world!</div>
            <BuilderComponent model="page" content={serverData.page} /> {/* Replace with your Builder.io model name */}
        </div>
    )
}

export async function getServerData() {
    try {
        const page =
            (await builder
                .get('page', {
                    userAttributes: {
                        urlPath: '/',
                    },
                })
                .toPromise()) || null

        return {
            props: {
                page,
            },
        }
    } catch (error) {
        console.error("Error fetching data:", error);
        return {
            props: {
                // Provide an empty object or handle the error as needed
                page: {}
            },
        }
    }
}
export default Page

Make sure to replace BUILDER_PUBLIC_KEY with your own Builder.io public key.

This code sets up a page component using Builder.io. It imports the React library and the BuilderComponent from the @builder.io/react library, initializes Builder.io with the provided public key, and creates a page component that renders a “Hello world!” div and the Builder.io component with the specified model. The getServerData() function is an async function from Gatsby that fetches data from the Builder.io model and provides it as props to the page component.

serverData is a keyword, and every time a user visits the index page, the getServerData() method is called, and the response is available as serverData on the page.

Step 4: Run the Application

Run the application by executing the following command in your terminal:

npm run develop

Your app should now be up and running at localhost:8000.

Step 5: Create a Page Model on Builder.io

Follow the video reference below to create a Page model on your Builder.io space and add some elements:

Documentation: Create Page

In the video, I’m using a page model with the name page and creating content for that page with text and image elements. Once you’ve added the elements, go ahead and Publish the page.

Video Tutorial: Creating a Page Model

Step 6: Making Changes to Your Page Data/Elements

You can now make changes to your page’s data/elements, and you should be able to see these updates reflected on your website.

Video Tutorial: Updating Page Data/Elements

A heads-up about Gatsby SSR: it currently doesn’t support GraphQL queries for server-side rendering (SSR). As a result, certain dynamic data won’t be available during the initial page load.

Additionally, To utilize Gatsby’s Server-Side APIs, it’s essential to work with the file named gatsby-ssr.jsx/gatsby-ssr.tsx. This file provides the capability to modify the content of static HTML files during the Server-Side Rendering (SSR) process carried out by Gatsby and Node.js. To make use of the Gatsby SSR APIs, all you need to do is create a file named gatsby-ssr.js in the root directory of your website. You have the flexibility to choose between JavaScript and TypeScript for this file.

It’s worth noting that the APIs wrapPageElement and wrapRootElement are accessible in both the SSR and browser APIs. It’s generally advisable to implement the same components in both the gatsby-ssr.js and gatsby-browser.js files to maintain consistency. This practice ensures that the pages generated through SSR with Node.js remain identical after being hydrated in the browser.

For more detailed information, please refer to the following link: Gatsby Server Rendering APIs | Gatsby

Happy building!