Initiating the Project
I'm starting the process with a focus on a blog project using Next.js and its ISR capabilities. The initial step involves fully understanding and embracing the core goal: showcasing Incremental Static Regeneration within the Next.js framework. I'm prioritizing clarity on the project's purpose.
Analyzing ISR Implementation
I'm now diving deeper into the technical aspects. The user, based on their request, seems to want a practical, code-focused guide on ISR. I'm prioritizing the Next.js App Router for this. I'm focusing on core ISR concepts, including dynamic routing, data fetching (using mock data for simplicity), and the crucial revalidate interval, as well as the path generation. I'm aiming for a concise explanation of the 'how' behind revalidate, and its function.
Constructing the Outline
I'm solidifying the outline. It's becoming more concrete, and I've decided to leverage jsonplaceholder.typicode.com for a seamless data source integration. I'm focusing on simplicity and clarity, ensuring the user can easily replicate the tutorial steps. I'm streamlining the process to create the project, fetch data, and build both the listing and single-post pages. I'm also planning a section on verifying that the ISR functionality is operating as expected. I'm now translating the outline to a mental code simulation to make sure this all works.
Deepening ISR Insights
I'm focusing now on the fundamental concepts of ISR, emphasizing its behavior in real-world scenarios. Specifically, I'm illustrating the process of building the site, caching content, and demonstrating how updates trigger revalidation. I'm prioritizing scenarios like User A seeing stale content, followed by background regeneration, and then User B seeing fresh content. I'm also planning to define ISR in the App Router's context. I'll need to define it as caching/revalidating, but the underlying concept remains the same.
Clarifying Code Structure
I'm now revising my coding strategy. Specifically, I'm switching completely to the App Router's syntax. I'll utilize the fetch API alongside the revalidate tag for static site generation. For code clarity, I'm organizing the project with a types.ts, a centralized lib/posts.ts for fetching, a listing page at app/page.tsx, and a detail page at app/blog/[id]/page.tsx. I'm also planning to use a time display to demonstrate ISR's behavior in action - dynamic timestamps will confirm regeneration. I'm focusing on the first 10 articles as an initial listing.
Emphasizing Production Build
I'm now focusing on production deployment. It's crucial for the user to understand that development mode behaves differently, especially concerning caching. To demonstrate the true ISR behavior, I'll emphasize using npm run build followed by npm start. This ensures the blog project accurately reflects ISR's functionality as it will be deployed, and offers a proper demonstration to the user.
This guide will walk you through building a Next.js 14+ (App Router) blog platform using ISR (Incremental Static Regeneration).
We will use the modern App Router, where ISR is implemented via the fetch API's revalidate option rather than the legacy getStaticProps.
Project Overview
We will build a blog that fetches data from a mock API (jsonplaceholder).
- Home Page: Lists all blog posts. Revalidates every 60 seconds.
- Post Detail Page: Shows individual post content. Revalidates every 60 seconds.
- Timestamp Indicator: We will render the time the page was generated to visually prove ISR is working.
Step 1: Setup the Project
Run the following commands in your terminal:
npx create-next-app@latest next-isr-blog
# Select: TypeScript, Tailwind, App Router -> YES
cd next-isr-blog
Step 2: Define Types and Fetch Logic
It is good practice to separate your data fetching logic. We will use jsonplaceholder for dummy data.
Create a file lib/getPosts.ts:
// lib/getPosts.ts
export type Post = {
userId: number;
id: number;
title: string;
body: string;
};
// Helper to simulate a slow database connection
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
export async function getAllPosts() {
await delay(1000); // Simulate slow network
// ISR MAGIC HAPPENS HERE via 'revalidate'
const res = await fetch('https://jsonplaceholder.typicode.com/posts', {
next: { revalidate: 60 }, // Revalidate every 60 seconds
});
if (!res.ok) throw new Error('Failed to fetch posts');
return res.json();
}
export async function getPost(id: string) {
await delay(1000);
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
next: { revalidate: 60 }, // Revalidate this specific post every 60s
});
if (!res.ok) return undefined;
return res.json();
}
Step 3: Build the Blog Listing (Home Page)
Edit app/page.tsx. We will display a list of posts and a timestamp to show when the static page was built.
// app/page.tsx
import Link from 'next/link';
import { getAllPosts, Post } from '@/lib/getPosts';
export default async function Home() {
const posts: Post[] = await getAllPosts();
// This timestamp will stay the same for 60 seconds
const timeGenerated = new Date().toLocaleTimeString();
return (
<main className="p-10 max-w-4xl mx-auto">
<div className="mb-8 text-center border-b pb-4">
<h1 className="text-4xl font-bold mb-2">My ISR Blog</h1>
<p className="text-sm text-gray-500">
Page generated at: <span className="font-bold text-red-500">{timeGenerated}</span>
</p>
<p className="text-xs text-gray-400 mt-1">
(Refresh exactly 60s after generation to see this time update)
</p>
</div>
<div className="grid gap-4">
{posts.slice(0, 10).map((post) => ( // Limiting to 10 for demo
<Link
key={post.id}
href={`/blog/${post.id}`}
className="block p-6 bg-slate-100 rounded-lg hover:bg-slate-200 transition"
>
<h2 className="font-semibold capitalize">{post.title}</h2>
</Link>
))}
</div>
</main>
);
}
Step 4: Build the Single Post Page
Create the directory structure app/blog/[id]/page.tsx. This handles dynamic routing.
We will also use generateStaticParams to tell Next.js to build certain pages at Build Time, while leaving the rest to be built on demand (ISR).
// app/blog/[id]/page.tsx
import { getAllPosts, getPost, Post } from '@/lib/getPosts';
import Link from 'next/link';
import { notFound } from 'next/navigation';
// 1. Tell Next.js which paths to pre-render at BUILD time.
// We are only pre-rendering the first 5 posts.
// Posts 6+ will be generated upon the first request (ISR).
export async function generateStaticParams() {
const posts: Post[] = await getAllPosts();
return posts.slice(0, 5).map((post) => ({
id: post.id.toString(),
}));
}
export default async function BlogPost({ params }: { params: { id: string } }) {
const post = await getPost(params.id);
if (!post) {
notFound();
}
const timeGenerated = new Date().toLocaleTimeString();
return (
<main className="p-10 max-w-2xl mx-auto">
<div className="mb-6">
<Link href="/" className="text-blue-500 hover:underline">
← Back to Home
</Link>
</div>
<article className="prose lg:prose-xl">
<h1 className="text-3xl font-bold capitalize mb-4">{post.title}</h1>
<p className="text-gray-700 leading-relaxed">{post.body}</p>
</article>
<div className="mt-10 border-t pt-4 text-sm text-gray-500 text-center">
<p>Static Page Generated at: <span className="font-bold text-red-500">{timeGenerated}</span></p>
<p className="text-xs mt-1">This page caches for 60 seconds.</p>
</div>
</main>
);
}
Step 5: Testing ISR (Important)
To see ISR in action, you cannot use npm run dev. In development mode, Next.js behaves differently and does not cache effectively to help you debug.
You must create a production build:
-
Build the project:
npm run build
Look at the terminal output. You will see ● (SSG) and circles.
- Posts 1-5 will be marked as generated.
- Posts 6-10 (which we didn't return in
generateStaticParams) are not generated yet.
-
Start the production server:
npm start
-
Verify Behavior:
- Open
http://localhost:3000. Note the red timestamp.
- Refresh the page immediately. The timestamp should NOT change. (It is serving the static HTML).
- Wait 61 seconds.
- Refresh the page. The timestamp will update. Next.js regenerated the page in the background.
- Click on Post #1 (Pre-rendered). It loads instantly.
- Click on Post #7 (Not pre-rendered). It might take a split second longer (the first time), then it generates the static file and caches it for subsequent visitors.
How ISR works in this code
- First Request: The user visits the page. Next.js serves the static HTML generated at build time.
- Within 60s: Any other user visiting gets the exact same HTML file (super fast). No API calls are made.
- After 60s (Stale): User A visits. They still see the old (stale) page. However, in the background, Next.js triggers a rebuild of the page.
- Regeneration: Next.js fetches new data from the API and generates new HTML.
- Update: Once the new HTML is ready, Next.js swaps the old file with the new one. User B (and all future users) will now see the updated content.