Logo

dev-resources.site

for different kinds of informations.

Static Site Generation

Published at
8/4/2024
Categories
staticwebapps
sre
gatsby
Author
suhaspalani
Categories
3 categories in total
staticwebapps
open
sre
open
gatsby
open
Author
11 person written this
suhaspalani
open
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.
gatsby Article's
30 articles in total
Favicon
Game Vault APK
Favicon
From Gatsby to Next.js: Why We Migrated Our Blog and How You Can Too
Favicon
Gatsby.js Overview: The Fast and Scalable Static Site Generator for React
Favicon
Advanced Rendering Techniques in Next.js, React, and Gatsby: A comprehensive guide for experienced developers.
Favicon
Getting Started with Strapi and Gatsby
Favicon
In-Depth Analysis of Next.js, Gatsby, and Remix
Favicon
You can stop complaining about WordPress and start using BCMS 🎉
Favicon
Data Display in Gatsby
Favicon
External content for GatsbyJS
Favicon
Best React Frameworks: Which One Should You Choose and When?
Favicon
Migrating my blog from Gatsby to Astro
Favicon
สูตรสล็อต pg เว็บตรง ทดสอบเล่นฟรี แบบไม่ต้องเสียค่าใช้จ่าย
Favicon
Static Site Generation
Favicon
Resolving NPM ERESOLVE Peer Dependency Issues in Node.js Projects
Favicon
A tale about migrating a 200 entries Gatsby blog untouched for 3 years to Astro
Favicon
Adding Social Media Images to a Gatsby Site
Favicon
Trik Jitu Memilih Situs Judi Online Terpercaya untuk Pengalaman Bermain yang Aman dan Seru
Favicon
Trik Jitu Memilih Situs Judi Online Terpercaya untuk Pengalaman Bermain yang Aman dan Seru
Favicon
Building static websites
Favicon
The unspoken issue with using documentToReactComponents with the Contentful Javascript client
Favicon
5 Best Websites for Free Gatsby Templates
Favicon
Replatforming from Gatsby to Zola!
Favicon
Gatsby blog: Building SEO-friendly blog with BCMS code starter
Favicon
Gatsby and Next.js
Favicon
Next.js vs Gatsby.js – which one to choose in 2024?
Favicon
Next.Js Vs Gatsby.Js Key-Difference, Advantages-Disadvantages, Limitations
Favicon
Photo Gallery Migration: Gatsby to Astro Follow-Up
Favicon
Another Migration: From Gatsby to Astro
Favicon
Next.js vs. Gatsby: Choosing the Right Framework for Your Project
Favicon
Keys and Tips for Migrating a WordPress Site to Gatsby Without Losing SEO Quality.

Featured ones: