The user wants a Next.js project that implements Incremental Static Regeneration (ISR) for a blog platform.
Key Requirements:
- Framework: Next.js (specifically looking for the Pages Router or App Router approach, but Pages Router is often the classic example for ISR basics, while App Router uses
revalidate. I should probably show the Pages Router approach as it's the most direct mapping to "ISR" terminology historically, or provide a modern App Router example. Given the "ISR" keyword, Pages Router is often what people look for first, but App Router is the future. I will stick to the Pages Router for clarity on specific functions like getStaticProps and getStaticPaths, as this is the standard ISR pattern). Self-correction: I'll add a note about App Router parity.
- Feature: Incremental Static Regeneration (ISR).
- Domain: Blog Platform.
- Components:
- List of posts (Home page).
- Individual post pages (Dynamic routes).
- Mock API/Data source (since I don't have a real backend).
- Explanation of how the revalidation works.
Step-by-Step Plan:
- Project Setup:
create-next-app.
- Mock Data: Create a simple utility to simulate fetching data from a database/API. This data needs to change slightly over time (or have a timestamp) to prove ISR is working.
- Home Page (Index): Show a list of blog posts.
- Use
getStaticProps.
- Set
revalidate (e.g., 10 seconds).
- Post Page (Dynamic): Show a single post.
- Use
getStaticPaths (fallback: 'blocking' or true).
- Use
getStaticProps with revalidate.
- UI: Basic styling (Tailwind or plain CSS modules) to make it readable.
- Instructions: How to run and how to verify the ISR behavior (checking timestamps).
Technical Details to Emphasize:
revalidate key in getStaticProps.
fallback in getStaticPaths.
- The difference between Build Time and Request Time.
Drafting the Code Structure:
lib/posts.js: Mock data functions.
pages/index.js: Home.
pages/posts/[slug].js: Detail page.
package.json: Dependencies.
Refining the Mock Data:
To prove ISR works, the page needs to display a "Generated at" timestamp. If the user refreshes before the revalidation window, the time stays the same. If they wait and refresh, the time updates (after the initial request triggers the regeneration).
App Router vs. Pages Router:
The prompt asks for a "Next.js project using ISR". The term "ISR" is heavily tied to getStaticProps.
However, Next.js 13/14/15 (App Router) handles this via fetch caching or next.revalidate.
Decision: I will provide the Pages Router implementation. It is the canonical implementation of ISR and easier to demonstrate distinctly from Server Side Rendering (SSR). I will mention the App Router alternative briefly.
Code Content:
lib/data.js: Needs to return a list of slugs and content.
pages/index.js:
export async function getStaticProps() { return { props: { ... }, revalidate: 10 } }
- Display posts.
pages/blog/[id].js:
getStaticPaths: Return known paths, set fallback: 'blocking' (allows new posts to be generated statically on first request).
getStaticProps: revalidate: 10.
- Display content + Build Time.
Final Review of the Output:
- Prerequisites (Node.js).
- Setup commands.
- File structure.
- Code blocks.
- How to test/verify.
Let's write the solution.
Here is a complete, step-by-step guide to building a Next.js blog platform using Incremental Static Regeneration (ISR).
We will use the Pages Router (pages/ directory) as it offers the most explicit and standard implementation of ISR logic via getStaticProps.
Prerequisites
- Node.js installed (v18 or newer).
Step 1: Initialize the Project
Open your terminal and run:
npx create-next-app@latest my-isr-blog
# Select 'No' for TypeScript (for simplicity in this guide)
# Select 'Yes' for ESLint
# Select 'No' for Tailwind CSS (we will use plain CSS modules)
# Select 'Yes' for `src/` directory (Optional, but I will assume standard root structure here)
# Select 'No' for App Router (We want Pages Router for this specific demo)
# Select 'Yes' to customize import alias (keep default @/*)
Navigate into the folder:
cd my-isr-blog
Step 2: Create Mock Data
In a real app, you would fetch data from a CMS (like Contentful or Sanity) or a database. For this demo, we will create a local file to simulate an external API.
Create a file named data.js in the root (or inside a lib folder).
lib/data.js
// Simulating a database that might change
let posts = [
{
id: 1,
slug: 'first-post',
title: 'My First Post',
content: 'This is the content of the first post. It was generated at build time.',
updatedAt: new Date().toISOString()
},
{
id: 2,
slug: 'second-post',
title: 'Understanding ISR',
content: 'Incremental Static Regeneration allows you to update static pages after you have built your site.',
updatedAt: new Date().toISOString()
}
];
export function getAllPosts() {
return posts.map(post => ({
slug: post.slug,
title: post.title
}));
}
export function getPostBySlug(slug) {
return posts.find(post => post.slug === slug);
}
// Function to simulate updating data in the DB
export function updatePostContent(slug, newContent) {
const post = posts.find(p => p.slug === slug);
if (post) {
post.content = newContent;
post.updatedAt = new Date().toISOString();
}
return post;
}
Step 3: Create the Blog Index Page (Homepage)
This page will list all posts. We will set a revalidation time of 10 seconds.
pages/index.js
import Link from 'next/link';
import { getAllPosts } from '../lib/data';
export default function Home({ posts }) {
return (
<div style={{ padding: '2rem', fontFamily: 'sans-serif' }}>
<h1>My ISR Blog</h1>
<p><i>Data cached. Regenerates every 10 seconds.</i></p>
<ul style={{ lineHeight: '2' }}>
{posts.map((post) => (
<li key={post.slug}>
<Link href={`/blog/${post.slug}`}>
{post.title}
</Link>
</li>
))}
</ul>
</div>
);
}
// This function runs at build time on the server
export async function getStaticProps() {
const posts = getAllPosts();
return {
props: {
posts,
},
// Next.js will attempt to re-generate the page:
// - When a request comes in
// - At most once every 10 seconds
revalidate: 10,
};
}
Step 4: Create Dynamic Blog Pages
This is where ISR shines. We pre-render paths known at build time, but allow new paths to be generated on demand if requested (using fallback: 'blocking').
pages/blog/[slug].js
import { getAllPosts, getPostBySlug } from '../../lib/data';
export default function BlogPost({ post }) {
if (!post) return <div>Loading...</div>;
return (
<div style={{ padding: '2rem', fontFamily: 'sans-serif' }}>
<h1>{post.title}</h1>
<small style={{ color: 'gray' }}>
Last Generated: {post.updatedAt}
</small>
<hr />
<p>{post.content}</p>
<a href="/">← Back to home</a>
</div>
);
}
// Define which paths to pre-render at build time
export async function getStaticPaths() {
const posts = getAllPosts();
// Generate paths for existing posts
const paths = posts.map((post) => ({
params: { slug: post.slug },
}));
return {
paths,
// 'blocking' means: if a user requests a page not in 'paths' (like a new post),
// Next.js will server-render it first, cache it, and then serve it.
fallback: 'blocking',
};
}
// Fetch data for a single post
export async function getStaticProps({ params }) {
const post = getPostBySlug(params.slug);
if (!post) {
return {
notFound: true,
};
}
return {
props: {
post,
},
// Revalidate this specific page every 10 seconds
revalidate: 10,
};
}
Step 5: Adding an "Update" Feature (Optional)
To prove the ISR works without rebuilding the app, we need a way to change the data in memory. We can create a simple API route to update our mock data.
pages/api/update.js
import { updatePostContent, getPostBySlug } from '../../lib/data';
export default function handler(req, res) {
if (req.method === 'POST') {
const { slug, content } = req.body;
// Update the in-memory data
const updatedPost = updatePostContent(slug, content);
// IMPORTANT: In a real app, you would use On-Demand ISR here:
// await res.revalidate(`/blog/${slug}`);
res.status(200).json({ message: 'Data updated in memory', post: updatedPost });
} else {
res.status(405).json({ message: 'Method not allowed' });
}
}
Step 6: Running and Testing
-
Run the dev server:
npm run dev
Note: In development mode (npm run dev), pages regenerate on every request to help you debug. To see actual ISR caching behavior, you must build and start the production version.
-
Build for Production:
Stop the server and run:
npm run build
npm start
-
The Test:
- Open your browser to
http://localhost:3000.
- Note the time displayed or the content.
- Refresh immediately: The time/content stays the same (It is cached).
- Wait 10 seconds and refresh: The initial refresh might still show the old cache, but if you trigger the regeneration logic (in a real app, this happens automatically after the
revalidate time passes and a request hits the server), the page will update.
- Since we are using mock data in server memory, restarting the server resets the data.
How to trigger On-Demand ISR (Real World)
In a production Headless CMS setup, you wouldn't rely on the 10-second timer. You would use a Webhook.
When you publish an article in your CMS:
- The CMS sends a POST request to your Next.js API (e.g.,
/api/revalidate).
- Your API route calls
res.revalidate('/blog/new-post').
- The static page is immediately updated in the cache, without waiting for the 10-second window.
Summary of Key Concepts
getStaticProps: Tells Next.js to render the page as static HTML.
revalidate: 10: Tells Next.js to regenerate this page in the background if a request comes in and the cached version is older than 10 seconds.
getStaticPaths: Defines the list of paths to be statically generated.
fallback: 'blocking': Ensures that if a new blog post URL is requested that wasn't built initially, Next.js will render it on the fly, cache it, and serve it (effectively making it part of the static build retroactively).