How SSG Works
How SSG Works
HTML is generated at build time and served from CDN.
SSG Process
1. Build time: Generate HTML for all pages
2. Deploy: Upload static files to CDN
3. Request: CDN serves pre-built HTML
4. Client: JavaScript hydrates HTML
Next.js SSG
// pages/products.js
export async function getStaticProps() {
const products = await fetchProducts();
return {
props: { products },
};
}
export default function Products({ products }) {
return (
<div>
<h1>Products</h1>
<ProductList products={products} />
</div>
);
}
Dynamic Routes with SSG
// pages/products/[id].js
export async function getStaticPaths() {
const products = await fetchAllProducts();
return {
paths: products.map(p => ({
params: { id: p.id.toString() },
})),
fallback: false, // 404 for unknown paths
};
}
export async function getStaticProps({ params }) {
const product = await fetchProduct(params.id);
return {
props: { product },
};
}
export default function Product({ product }) {
return (
<div>
<h1>{product.name}</h1>
<p>{product.description}</p>
</div>
);
}
Build Output
/
index.html
products.html
products/1.html
products/2.html
products/3.html
Deployment
# Build
npm run build
# Export static files
npm run export
# Deploy to CDN
npx netlify deploy --prod --dir=out
SSG Benefits
- Fastest performance: Pre-built HTML
- Great SEO: Full HTML available
- Easy scaling: CDN handles traffic
- Low cost: No server needed
SSG Benefits
SSG Benefits
Performance Benefits
// Time to First Byte (TTFB)
// CSR: 200-500ms (server processing)
// SSR: 100-300ms (server rendering)
// SSG: 10-50ms (CDN response)
// First Contentful Paint (FCP)
// CSR: 1-3s (JavaScript execution)
// SSR: 0.5-1s (HTML + hydration)
// SSG: 0.1-0.3s (immediate HTML)
Caching Benefits
CDN Cache:
- Hit ratio: 95%+ for static sites
- Global distribution
- Instant response
Browser Cache:
- Immutable assets
- Long cache lifetime
- Offline support
Cost Benefits
| Hosting | Monthly Cost |
|---|---|
| Node.js Server | $20-100+ |
| Serverless Functions | $5-50 |
| Static CDN | $0-20 |
Security Benefits
- No server-side code: Nothing to hack
- No database: No SQL injection
- CDN protection: DDoS mitigation
- Simple attack surface: Static files only
Developer Experience
# Local development
npm run dev
# Build for production
npm run build
# Preview production build
npm run preview
# Deploy
npm run deploy
Limitations
- Build time: Pages generated at build
- Not for real-time data: Content stale between builds
- Large sites: Long build times
- Dynamic content: Needs ISR or SSR
Dynamic SSG
Dynamic SSG
Use Incremental Static Regeneration (ISR) for dynamic content.
ISR Basics
// Revalidate every 60 seconds
export async function getStaticProps() {
const products = await fetchProducts();
return {
props: { products },
revalidate: 60, // seconds
};
}
On-Demand Revalidation
// pages/api/revalidate.js
export default async function handler(req, res) {
const { secret, path } = req.body;
if (secret !== process.env.REVALIDATION_SECRET) {
return res.status(401).json({ message: 'Invalid token' });
}
await res.revalidate(path || '/products');
return res.json({ revalidated: true });
}
Fallback Pages
// pages/products/[id].js
export async function getStaticPaths() {
const products = await fetchPopularProducts();
return {
paths: products.map(p => ({
params: { id: p.id.toString() },
})),
fallback: 'blocking', // SSR for unknown paths
};
}
export async function getStaticProps({ params }) {
const product = await fetchProduct(params.id);
if (!product) {
return { notFound: true };
}
return {
props: { product },
revalidate: 3600,
};
}
ISR Strategies
// Time-based revalidation
revalidate: 60 // Every minute
revalidate: 3600 // Every hour
revalidate: 86400 // Every day
// On-demand revalidation
// Trigger via API when content changes
// Tag-based revalidation (Next.js 13+)
export async function getStaticProps() {
const products = await fetchProducts();
return {
props: { products },
tags: ['products'],
};
}
// Revalidate by tag
await res.revalidate('/products', { tags: ['products'] });
ISR vs SSR
| Aspect | ISR | SSR |
|---|---|---|
| Performance | CDN speed | Server speed |
| Freshness | Configurable | Always fresh |
| Cost | Low | Higher |
| Complexity | Simpler | More complex |
Practice Problems
Create a reusable React component implementing Static Site Generation. Include proper state management and accessibility.
Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where neededWrite unit and integration tests for Static Site Generation using React Testing Library.
Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility testsOptimize Static Site Generation for performance. Consider memoization, code splitting, and bundle size.
Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysisQuiz
1. When is HTML generated in SSG?
2. What is ISR?
3. What is the primary purpose of Static Site Generation?
4. What is a common mistake when implementing Static Site Generation?
Flashcards
Question
What is SSG?
Click to reveal answer
Answer
Static Site Generation - HTML is generated at build time and served from CDN.
Question
What are the benefits of SSG?
Click to reveal answer
Answer
Fastest performance, great SEO, easy scaling, low cost, and simple security.
Question
What is ISR?
Click to reveal answer
Answer
Incremental Static Regeneration - updates static pages after build time without full rebuilds.
Question
When should you use ISR over SSG?
Click to reveal answer
Answer
When content changes frequently but you still want static site performance.
Question
What is Static Site Generation?
Click to reveal answer
Answer
Static Site Generation is a key concept in frontend development.
Revision Notes
Key Takeaways
- 1.SSG generates HTML at build time for fastest performance
- 2.SSG is served from CDN for global distribution
- 3.ISR allows static pages to update after build time
- 4.SSG is ideal for blogs, docs, and marketing sites
- 5.Use fallback for dynamic routes not pre-rendered
Interview Tips
- •Explain how SSG works and its benefits
- •Discuss ISR and when to use it
- •Know the difference between SSG and SSR
Cheat Sheet
SSG Cheat Sheet
How SSG Works
- Build: Generate HTML
- Deploy: Upload to CDN
- Request: CDN serves HTML
- Client: JavaScript hydrates
Benefits
- Fastest performance
- Great SEO
- Easy scaling
- Low cost
ISR
return {
props: { data },
revalidate: 60
};
Use Cases
- Blogs
- Documentation
- Marketing sites
- E-commerce (with ISR)