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.
staticwebapps Article's
30 articles in total
Favicon
Configuring a custom domain for your Azure Static Web App
Favicon
Building an educational game with AI tools and Azure Static Web Apps (Part 1)
Favicon
Building an educational game with AI tools and Azure Static Web Apps (Part 2)
Favicon
Static React App Deployment with Vite
Favicon
Transform Your Cloud Migration Strategy: Transition Microsoft workloads to Linux on AWS with AI Solutions
Favicon
Building Domain-Specific AI Models: A Guide for Specialized Industries
Favicon
Crypto Trading
Favicon
On-demand App Development For a Small Business
Favicon
How to Drive Quality Leads with Social Media | Connect Infosoft
Favicon
Tiiny Host Alternatives: Why Static.app is Better
Favicon
ELEVENS4D - Slot Scatter Hitam, Bocoran RTP Akurat, dan Slot PGSoft Terbaru
Favicon
Introducing svelte-bundle
Favicon
End Point Security Solutions
Favicon
A SocialBook where you connect with world.
Favicon
Make your web page faster
Favicon
CapCut APK Website Performance Issues: Seeking Solutions
Favicon
Deploying Static Files for Website Hosting in SafeLine
Favicon
Testing and Debugging: Strategies to Ensure Web Application Quality
Favicon
Testing and Debugging: Strategies to Ensure Web Application Quality
Favicon
How to use the HTML datalist tag
Favicon
Hosting a Static website on a private Amazon S3 bucket using CloudFront’s OAC
Favicon
Deploy Your Static Web App on AWS S3 in just 10 Minutes
Favicon
External content for GatsbyJS
Favicon
Cloud Resume Challenge pt 4: Spinning up an Azure Static Web App
Favicon
Window swap html css js
Favicon
Step-by-Step Guide: Hosting Static Webapps on Azure
Favicon
Building My First Static Website
Favicon
Static Site Generation
Favicon
Guía Completa para Crear una Web Estática con AWS S3 y AWS CLI
Favicon
HOST A STATIC WEBSITE ON AZURE BLOB STORAGE

Featured ones: