DEV Community

Cover image for Static Site Generation
Suhas Palani
Suhas Palani

Posted on

Static Site Generation

Static Site Generation with Gatsby

In this post, I will explore static site generation (SSG) using Gatsby, a powerful React-based framework. I'll cover the basics of SSG, set up a Gatsby project, and delve into creating and deploying static sites with Gatsby.

1. Introduction to Static Site Generation (SSG)

What is Static Site Generation (SSG)?

Static Site Generation involves pre-rendering web pages at build time, producing static HTML files. This can lead to significant performance improvements and better security compared to dynamically generated pages.

Benefits of SSG:

  • Fast Load Times: Pre-rendered pages load faster as they are served directly as static HTML.
  • Enhanced Security: No server-side processing, reducing attack vectors.
  • SEO-Friendly: Static pages are easily crawled and indexed by search engines.

2. Introduction to Gatsby

Gatsby is a React-based open-source framework for building fast, secure, and scalable websites. It leverages the power of React and GraphQL to create static sites with dynamic capabilities.

Key Features of Gatsby:

  • Static Site Generation: Pre-rendering pages at build time.
  • React-based: Leverage the React ecosystem and component-based architecture.
  • GraphQL: Query data from multiple sources with ease.
  • Plugins: Rich ecosystem of plugins for extended functionality.

3. Setting Up a Gatsby Project

Prerequisites:

  • Node.js and npm/yarn installed.

Steps to create a new Gatsby project:

npm install -g gatsby-cli
gatsby new my-gatsby-site
cd my-gatsby-site
gatsby develop
Enter fullscreen mode Exit fullscreen mode

Project Structure Overview:

  • src/: Directory for source code including pages, components, and styles.
  • static/: Directory for static assets.
  • gatsby-config.js: Configuration file for plugins and site metadata.

4. Creating Your First Page

Create an index.js file inside the src/pages/ directory:

// src/pages/index.js
import React from 'react';

const Home = () => {
  return (
    <main>
      <h1>Welcome to My Gatsby Site!</h1>
      <p>This is your first Gatsby page.</p>
    </main>
  );
};

export default Home;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Basic structure of a Gatsby page component.
  • src/pages/: Directory for page components.

5. Using Gatsby's GraphQL Data Layer

Gatsby uses GraphQL to manage and query data from various sources. Let's create a simple page that fetches site metadata.

Adding Site Metadata:
Update gatsby-config.js:

module.exports = {
  siteMetadata: {
    title: 'My Gatsby Site',
    description: 'A simple static site built with Gatsby',
    author: 'Your Name',
  },
  plugins: [
    // Add plugins here
  ],
};
Enter fullscreen mode Exit fullscreen mode

Querying Site Metadata with GraphQL:
Create a header.js component:

// src/components/header.js
import React from 'react';
import { graphql, useStaticQuery } from 'gatsby';

const Header = () => {
  const data = useStaticQuery(graphql`
    query {
      site {
        siteMetadata {
          title
        }
      }
    }
  `);

  return <header>{data.site.siteMetadata.title}</header>;
};

export default Header;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • useStaticQuery: Hook for querying GraphQL data in components.
  • Querying site metadata defined in gatsby-config.js.

6. Creating Dynamic Pages

Gatsby can generate dynamic pages using templates and GraphQL queries.

Creating a Markdown Blog:
Install necessary plugins:

npm install gatsby-transformer-remark gatsby-source-filesystem
Enter fullscreen mode Exit fullscreen mode

Update gatsby-config.js with plugins:

module.exports = {
  siteMetadata: {
    title: 'My Gatsby Site',
    description: 'A simple static site built with Gatsby',
    author: 'Your Name',
  },
  plugins: [
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'posts',
        path: `${__dirname}/src/posts/`,
      },
    },
    'gatsby-transformer-remark',
  ],
};
Enter fullscreen mode Exit fullscreen mode

Create Markdown files in src/posts/:

// src/posts/hello-world.md
---
title: "Hello World"
date: "2024-07-12"
---

This is my first blog post in Gatsby!
Enter fullscreen mode Exit fullscreen mode

Create a blog template:

// src/templates/blog-post.js
import React from 'react';
import { graphql } from 'gatsby';

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

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

export default BlogPost;
Enter fullscreen mode Exit fullscreen mode

Add a gatsby-node.js file to generate pages:

const path = require('path');

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

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

exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions;
  if (node.internal.type === 'MarkdownRemark') {
    const slug = createFilePath({ node, getNode, basePath: 'posts' });
    createNodeField({
      node,
      name: 'slug',
      value: slug,
    });
  }
};
Enter fullscreen mode Exit fullscreen mode

7. Deploying Your Gatsby Site

Gatsby sites can be deployed to various hosting providers like Netlify, Vercel, and GitHub Pages.

Deploying to Netlify:

  1. Create a new site on Netlify.
  2. Connect your GitHub repository.
  3. Configure the build settings: gatsby build.
  4. Deploy the site.

Deploying to Vercel:

  1. Create a new project on Vercel.
  2. Import your GitHub repository.
  3. Configure the build settings: npm run build.
  4. Deploy the site.

8. Best Practices for Gatsby

Best Practices:

  • Optimize images using gatsby-plugin-image.
  • Leverage GraphQL for efficient data fetching.
  • Use plugins to extend functionality.
  • Follow the Gatsby best practices for SEO.

9. Conclusion

Summarize the key points covered:

  • Introduction to SSG and its benefits.
  • Setting up and creating pages with Gatsby.
  • Using GraphQL for data fetching.
  • Creating dynamic pages with templates.
  • Deploying Gatsby sites.

10. Additional Resources

  • Gatsby Documentation
  • Tutorials and guides on advanced Gatsby topics.
  • Community forums and support.

Top comments (0)