Server-Side Rendering with Gatsby

Server-Side Rendering (SSR) is a technique where HTML is generated on the server at runtime, which improves initial load times and SEO. Gatsby is a popular static site generator for React that uses a build-time approach to pre-render pages. This chapter will explore how Gatsby achieves high performance and SEO benefits through its static generation and how you can leverage these features for your projects.

Basics of Gatsby and SSR

What is Gatsby?

Description: Gatsby is a React-based open-source framework that enables you to build static websites and applications. It uses GraphQL to pull data from various sources, and it pre-renders pages into static HTML files during the build process.

Key Features:

  • Static site generation (SSG)
  • Built-in support for GraphQL
  • Plugins for adding functionality
  • Optimized for performance and SEO

What is Server-Side Rendering (SSR)?

Description: SSR refers to the process of generating HTML content on the server rather than in the browser. With SSR, the server sends a fully rendered page to the client, which can improve load times and SEO compared to client-side rendering (CSR).

How Gatsby Uses SSR

Gatsby primarily uses Static Site Generation (SSG) rather than traditional SSR. During the build process, Gatsby pre-renders all pages into static HTML files. This approach combines the benefits of SSR, such as fast initial load times and SEO advantages, with the advantages of static hosting.

Setting Up a Gatsby Project

Installing Gatsby

Steps:

  1. Install Gatsby CLI globally using npm or yarn:

				
					npm install -g gatsby-cli

				
			

or

				
					yarn global add gatsby-cli

				
			

2 Create a new Gatsby project:

				
					gatsby new my-gatsby-site

				
			

3 Navigate to the project directory:

				
					cd my-gatsby-site

				
			

4 Start the development server

				
					gatsby develop

				
			

Explanation: This will create a new Gatsby site with a default configuration and start a local development server.

Understanding the Project Structure

Key Files and Directories:

  • src/pages/: Contains the React components that represent your pages.
  • gatsby-config.js: Configuration file where you can add plugins and site metadata.
  • gatsby-node.js: Contains Node.js APIs to programmatically create pages and handle SSR.
				
					yarn global add gatsby-cli

				
			

Creating Static Pages

Creating Pages

Example:

Create a new file src/pages/about.js:

				
					import React from 'react';

const AboutPage = () => (
  <div>
    <h1>About Us</h1>
    <p>This is the about page.</p>
  </div>
);

export default AboutPage;

				
			

Explanation: Gatsby will automatically generate a static HTML page for /about based on this React component.

Using Static Query

Description: Gatsby allows you to use static queries to fetch data at build time.

Example:

Create a file src/pages/index.js:

				
					import React from 'react';
import { graphql } from 'gatsby';

const IndexPage = ({ data }) => (
  <div>
    <h1>{data.site.siteMetadata.title}</h1>
    <p>Welcome to the homepage!</p>
  </div>
);

export const query = graphql`
  query {
    site {
      siteMetadata {
        title
      }
    }
  }
`;

export default IndexPage;

				
			

Explanation: This example uses a static GraphQL query to fetch site metadata and render it on the homepage.

Advanced Gatsby Features

Dynamic Pages with Gatsby Node API

Description: You can use the gatsby-node.js file to create dynamic pages based on data sources.

Example:

Create gatsby-node.js in the root directory:

				
					const path = require('path');

exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions;
  
  const result = await graphql(`
    query {
      allMarkdownRemark {
        edges {
          node {
            frontmatter {
              path
            }
          }
        }
      }
    }
  `);

  result.data.allMarkdownRemark.edges.forEach(({ node }) => {
    createPage({
      path: node.frontmatter.path,
      component: path.resolve(`./src/templates/blog-post.js`),
      context: {
        pathSlug: node.frontmatter.path,
      },
    });
  });
};

				
			

Explanation: This code creates pages dynamically based on markdown files. It uses a GraphQL query to fetch the paths and then uses the createPage API to generate pages.

Adding Server-Side Logic with Gatsby Functions

Description: Gatsby Functions allow you to add server-side logic such as API routes.

Example:

Create a new file src/api/hello.js:

				
					export default function handler(req, res) {
  res.status(200).json({ message: 'Hello World' });
}

				
			

Explanation: This file creates an API route that can be accessed as /api/hello in your deployed Gatsby site.

Handling Data Fetching

Description: Gatsby supports different ways to fetch data, including static queries, page queries, and source plugins.

Example:

For a page query

				
					import React from 'react';
import { graphql } from 'gatsby';

const BlogPost = ({ data }) => (
  <div>
    <h1>{data.markdownRemark.frontmatter.title}</h1>
    <div dangerouslySetInnerHTML={{ __html: data.markdownRemark.html }} />
  </div>
);

export const query = graphql`
  query($pathSlug: String!) {
    markdownRemark(frontmatter: { path: { eq: $pathSlug } }) {
      frontmatter {
        title
      }
      html
    }
  }
`;

export default BlogPost;

				
			

Explanation: This code fetches markdown data based on a slug and renders it as HTML.

Deploying Gatsby Sites

Using Gatsby Cloud

Description: Gatsby Cloud is a hosting service optimized for Gatsby sites.

Steps:

  1. Sign up for Gatsby Cloud.
  2. Connect your Git repository.
  3. Configure build settings and deploy.

Explanation: Gatsby Cloud offers optimized builds and previews, making it easier to deploy and manage your Gatsby site.

Deploying to Netlify

Description: Netlify is a popular platform for deploying static sites.

Steps:

  1. Push your Gatsby site to a Git repository.
  2. Log in to Netlify and link your Git repository.
  3. Configure build settings and deploy.

Explanation: Netlify provides a simple setup for continuous deployment and offers features like serverless functions and CDN.

Server-Side Rendering (SSR) in Gatsby enables the generation of dynamic content on the server at runtime, providing flexibility for applications that require user-specific data or frequently updated content. By leveraging SSR, developers can deliver faster initial load times, improved SEO, and a seamless user experience. Gatsby's SSR capabilities strike a balance between static site generation and dynamic rendering, making it an excellent choice for modern, performant web applications.Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India