0
0
NextJSframework~30 mins

On-demand revalidation in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
On-demand Revalidation in Next.js
📖 Scenario: You are building a blog with Next.js. You want to update the blog posts page when new posts are added without rebuilding the whole site manually.
🎯 Goal: Create a Next.js page that shows a list of blog posts. Add an API route that triggers on-demand revalidation to update the page when new posts are added.
📋 What You'll Learn
Create a Next.js page at app/posts/page.tsx that fetches and displays a list of posts.
Create a mock data array called posts with exact post titles.
Add a configuration variable revalidatePath with the path to revalidate.
Create an API route at app/api/revalidate/route.ts that calls Next.js revalidatePath to refresh the posts page.
Use export const revalidate = 0 in the posts page to enable on-demand revalidation.
💡 Why This Matters
🌍 Real World
On-demand revalidation lets websites update static pages instantly when content changes, without rebuilding the whole site. This is useful for blogs, news sites, and e-commerce.
💼 Career
Understanding on-demand revalidation is important for Next.js developers to build fast, dynamic sites that stay up-to-date with minimal delay.
Progress0 / 4 steps
1
Create the posts data array
Create a constant array called posts in app/posts/page.tsx with these exact strings: 'First Post', 'Second Post', and 'Third Post'.
NextJS
Need a hint?

Use const posts = ['First Post', 'Second Post', 'Third Post'];

2
Add the revalidate path variable
Add a constant called revalidatePath and set it to the string '/posts' in app/posts/page.tsx.
NextJS
Need a hint?

Write const revalidatePath = '/posts';

3
Create the posts page with revalidation export
In app/posts/page.tsx, export const revalidate = 0 to enable on-demand revalidation. Then create a default React component called PostsPage that returns a <main> element with an <h1> titled 'Blog Posts' and an unordered list <ul> showing each post from the posts array inside <li> elements.
NextJS
Need a hint?

Use export const revalidate = 0; and map over posts inside the component.

4
Create the API route for on-demand revalidation
Create a file app/api/revalidate/route.ts. Inside, export an async function called GET that accepts a Request parameter. Inside the function, call await res.revalidate(revalidatePath) to trigger revalidation of the /posts page. Then return a JSON response with { revalidated: true }. Import NextResponse from next/server and use it to return the JSON response.
NextJS
Need a hint?

Use export async function GET(request: Request) and call await res.revalidate(revalidatePath).