Static Site Generation (SSG)

Pre-built HTML at Build Time for Lightning-Fast Performance

⏱️ 10 minutes 🎯 JAMstack Focus ⚡ Build-time Generation

📄 What is Static Site Generation?

📋 Definition

Static Site Generation (SSG) is a web development approach where HTML pages are pre-generated at build time, creating static files that can be served directly from a CDN without any server processing.

🏗️ Build Process

1

Build Time

Fetch data & generate HTML

2

Static Files

HTML, CSS, JS generated

3

CDN Deploy

Files deployed globally

4

Instant Serve

Lightning-fast delivery

✨ Key Advantages

Lightning Fast

No server processing - files served directly from CDN

FCP: ~200ms
💰

Cost Effective

No server costs - host on CDN or static hosting

$0-5/month
🔒

Highly Secure

No server vulnerabilities - just static files

Attack surface: Minimal
🌍

Global Scale

CDN distribution ensures worldwide fast access

Latency: <50ms< /div>

🥞 JAMstack Architecture

J

JavaScript

Dynamic functionality and interactivity

React, Vue, Vanilla JS
+
A

APIs

Reusable APIs for dynamic content

REST, GraphQL, Serverless
+
M

Markup

Pre-built markup at build time

SSG, Markdown, CMS

🏁 Performance Showdown: SSG vs SSR vs CSR

⚡ Speed Comparison

📄 SSG
-
🖥️ SSR
-
💻 CSR
-

🏆 Race Results

Click "Start Performance Race" to see the results!

📊 Detailed Performance Metrics

Metric SSG SSR CSR
Time to First Byte 50ms 800ms 100ms
First Contentful Paint 200ms 900ms 1500ms
Largest Contentful Paint 400ms 1100ms 2200ms
Time to Interactive 800ms 1400ms 1500ms
Cumulative Layout Shift 0.01 0.05 0.08

💰 Infrastructure Cost Comparison

📄 SSG Hosting

$0-5/month
  • Netlify/Vercel free tier
  • GitHub Pages
  • AWS S3 + CloudFront
  • No server maintenance
Scales to millions of users

🖥️ SSR Hosting

$20-200+/month
  • Server instances required
  • Database hosting
  • Load balancers
  • Monitoring & maintenance
Costs scale with traffic

💻 CSR Hosting

$0-10/month
  • Static hosting for app
  • API backend required
  • CDN for assets
  • Simple deployment
API costs scale separately

🏗️ SSG Build Process Deep Dive

🔄 Complete Build Pipeline

📝

1. Content Sources

Markdown Files CMS APIs JSON Data External APIs
⚙️

2. Build Process

Fetch Data Generate Pages Optimize Assets Create Sitemap
📦

3. Static Output

index.html about.html blog/[slug].html assets/*
🌐

4. CDN Deployment

Global Distribution Edge Caching Auto Scaling

🎮 Interactive Build Simulation

🔧 Build Console Ready
$ npm run build
Waiting for build to start...

📁 Generated Files

📁 out/
📄 _next/
📄 index.html
📄 about.html
📄 404.html

📊 Build Statistics

Build Time: -
Pages Generated: -
Total Size: -
Avg Page Size: -

⚛️ Next.js SSG Implementation

🛠️ Next.js SSG Methods

getStaticProps

Fetch data at build time for static generation

export async function getStaticProps() {
  // Runs at build time
  const posts = await fetch('https://api.example.com/posts')
    .then(res => res.json());
  
  return {
    props: {
      posts,
    },
    // Regenerate page at most once per hour
    revalidate: 3600,
  };
}
✅ Build-time execution ✅ ISR support ✅ Fast delivery

getStaticPaths

Define which dynamic routes to pre-generate

export async function getStaticPaths() {
  // Get all blog post slugs
  const posts = await fetch('https://api.example.com/posts')
    .then(res => res.json());
  
  const paths = posts.map((post) => ({
    params: { slug: post.slug },
  }));
  
  return {
    paths,
    // Enable ISR for new pages
    fallback: 'blocking',
  };
}
✅ Dynamic routes ✅ Fallback options ✅ Scalable

🔄 Incremental Static Regeneration (ISR)

ISR allows you to update static content after you've built your site, without rebuilding the entire site.

T=0
Initial Build

Page generated at build time

Static HTML Ready
T=1hr
First Request After Revalidate

Serve stale content, trigger regeneration

Background Regeneration
T=1hr+5s
Subsequent Requests

Serve fresh, regenerated content

Updated Content Served

🎮 ISR Simulation

Page Status
Fresh
Last generated: Build time
Request Simulation
Requests: 0
Regenerations: 0

🛠️ SSG Frameworks & Tools Ecosystem

🚀 Popular SSG Frameworks

Next.js

React-based framework with hybrid rendering

✅ SSG + SSR + ISR ✅ API Routes ✅ Image Optimization ✅ TypeScript Support
Build Speed: Fast
Learning Curve: Medium
Ecosystem: Huge

Gatsby

GraphQL-powered static site generator

✅ GraphQL Data Layer ✅ Plugin Ecosystem ✅ Image Processing ✅ PWA Features
Build Speed: Slow
Learning Curve: Steep
Ecosystem: Rich

Nuxt.js

Vue.js framework with multiple rendering modes

✅ Vue Ecosystem ✅ Auto Routing ✅ Module System ✅ Static Generation
Build Speed: Fast
Learning Curve: Medium
Ecosystem: Growing

11ty (Eleventy)

Simple, flexible static site generator

✅ Template Agnostic ✅ Zero Config ✅ Fast Builds ✅ Minimal JS
Build Speed: Very Fast
Learning Curve: Easy
Ecosystem: Focused

🎯 Framework Selection Tool

What's your priority?

What type of site?

🎯 Recommended Framework

Select your priorities and site type to get a personalized recommendation!

⚠️ SSG Limitations & Modern Solutions

🚨 Common SSG Challenges

Stale Content

Problem: Content becomes outdated between builds

Impact: Users see old information

Blog Post Published: 2:00 PM
Last Build: 1:00 PM
❌ New post not visible until next build
🏗️

Long Build Times

Problem: Build time increases with content volume

Impact: Slow deployments and feedback loops

100 pages:
2 min
1,000 pages:
15 min
10,000 pages:
45+ min
🔄

Dynamic Content Challenges

Problem: User-specific content requires client-side rendering

Impact: Hybrid approach needed

Blog posts, product info
User profiles, cart items
💾

Build Resource Usage

Problem: Large sites require significant build resources

Impact: Higher CI/CD costs and complexity

CPU: High during builds
Memory: Scales with content
Build Time: Linear growth

🚀 Modern Solutions & Patterns

🔄

Incremental Static Regeneration

Update static pages on-demand without full rebuilds

export async function getStaticProps() {
  return {
    props: { data: await fetchData() },
    revalidate: 60, // Revalidate at most once per minute
  };
}
✅ Fresh content ✅ Fast builds ✅ Scalable
🏝️

Islands Architecture

Hydrate only interactive components, keep rest static

// Astro Islands example
---
import Counter from './Counter.jsx';
---

<html>
  <body>
    <h1>Static Content</h1>
    <Counter client:load />
    <p>More static content</p>
  </body>
</html>
✅ Minimal JS ✅ Fast hydration ✅ Better performance

Edge-Side Includes (ESI)

Combine static and dynamic content at the edge

// Edge function example
export default function handler(req) {
  const staticContent = getStaticContent();
  const userContent = getUserSpecificContent(req.user);
  
  return new Response(
    staticContent.replace('{{USER_CONTENT}}', userContent)
  );
}
✅ Personalization ✅ Edge performance ✅ Static base
🔧

Build Optimization

Parallel builds, incremental builds, and caching

// Parallel page generation
const pages = await Promise.all([
  generateHomePage(),
  generateAboutPage(),
  generateBlogPages(),
  generateProductPages()
]);

// Incremental builds
if (hasContentChanged('blog')) {
  await regenerateBlogPages();
}
✅ Faster builds ✅ Resource efficient ✅ Smart caching

📝 Headless CMS Integration

📝

Content Creation

Editors create content in headless CMS

Contentful Strapi Sanity Ghost
🔔

Webhook Trigger

CMS triggers build on content changes

// Webhook handler
export default async function webhook(req, res) {
  if (req.body.event === 'content.update') {
    await triggerBuild();
  }
  res.status(200).json({ received: true });
}
🏗️

Automated Build

Site rebuilds automatically with fresh content

Fetch CMS Data Generate Pages Deploy to CDN

🎮 CMS Integration Demo

📝 Headless CMS
🔔 Build Status
Ready
Waiting for content changes...
🌐 Generated Site
My Blog
Welcome to my blog

This is the initial post...

🏆 SSG Best Practices & Optimization

💡 Essential SSG Best Practices

🏗️ Build Optimization

Incremental Builds

Only rebuild changed pages to reduce build time

// Next.js incremental builds
module.exports = {
  experimental: {
    incrementalCacheHandlerPath: require.resolve('./cache-handler.js'),
  },
};
🔄
Smart Revalidation

Use appropriate revalidation strategies for different content types

News: 60 seconds
Products: 300 seconds
About Page: 1 day

📊 Performance Optimization

🖼️
Image Optimization

Automatic image optimization and responsive images

// Next.js Image component
import Image from 'next/image';

<Image
  src="/hero.jpg"
  alt="Hero image"
  width={800}
  height={400}
  priority
  placeholder="blur"
/>
📦
Bundle Optimization

Code splitting and tree shaking for minimal bundles

Before: 450kb
After: 180kb
Improvement: 60%

🔍 SEO & Discovery

🗺️
Automatic Sitemap Generation

Generate sitemaps automatically during build

// Generate sitemap
const sitemap = `
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  ${pages.map(page => `
    <url>
      <loc>${baseUrl}${page.slug}</loc>
      <lastmod>${page.lastModified}</lastmod>
    </url>
  `).join('')}
</urlset>`;
🏷️
Meta Tags & Open Graph

Dynamic meta tags for each generated page

<title>{post.title} | My Blog</title>
<meta property="og:title" content="{post.title}" />
<meta property="og:description" content="{post.excerpt}" />

✅ SSG Optimization Checklist

🚀 Performance

🔍 SEO

🏗️ Build Process

🎯 SSG Summary & When to Choose

📋 Key Takeaways

✅ SSG Strengths

  • Lightning-fast page loads
  • Excellent Core Web Vitals scores
  • Cost-effective hosting
  • High security (no server)
  • Global CDN distribution
  • Perfect SEO performance

❌ SSG Limitations

  • Content freshness depends on builds
  • Build times increase with content
  • Limited dynamic functionality
  • Complex user-specific content
  • Real-time features require CSR

🎯 SSG Use Case Matrix

Content Update Frequency
🟢 Perfect for SSG

Blogs, Documentation, Marketing Sites

🟡 Good with ISR

News Sites, E-commerce Catalogs

🔴 Consider SSR/CSR

Live Data, User Dashboards

🟡 Hybrid Approach

Corporate Sites, Portfolios

Interactivity Requirements

🚀 Modern SSG Deployment Strategies

Vercel

  • Zero-config deployments
  • Automatic ISR support
  • Edge functions
  • Preview deployments
Free tier: 100GB bandwidth
🌐

Netlify

  • Git-based deployments
  • Form handling
  • Serverless functions
  • Split testing
Free tier: 100GB bandwidth
☁️

AWS Amplify

  • Full AWS integration
  • CI/CD pipelines
  • Custom domains
  • Password protection
Pay per build minute
🐙

GitHub Pages

  • Free for public repos
  • GitHub Actions integration
  • Custom domains
  • Jekyll support
Free for public repos

🚀 Next: Explore API Integration Patterns

Learn modern data fetching strategies, React Query, SWR, and GraphQL integration patterns.

Continue to API Hooks →