Implement ISR in Next.js 15 with Strapi 5 webhooks
Learn step‑by‑step how to wire Strapi 5 webhooks to a Next.js 15 route handler, verify payloads, map events to revalidatePath or revalidateTag, and keep editorial workflows and content versioning in sync.
By the Revisionary team · · 4 min read
Incremental Static Regeneration (ISR) in Next.js 15 can be driven by Strapi 5 webhooks so that every publish, update or unpublish instantly revalidates the affected page or tag. By creating a secure API route that verifies the webhook signature, maps Strapi events to revalidatePath or revalidateTag, and respects Revisionary versioning, you get on‑demand fresh content without sacrificing the performance of static pages.
why ISR with Strapi matters
- Fast static pages – Next.js generates HTML at build time, delivering low‑latency responses.
- Fresh content – When editors publish a new version in Strapi, the static page is regenerated only for the changed route, not the whole site.
- Editorial safety – Revisionary keeps every version, so you can trigger revalidation only after a review stage passes.
- Type‑safety – Using TypeScript for both the webhook handler and Strapi client prevents runtime mismatches.
prerequisites
| Requirement | Details |
|---|---|
| Strapi | v5 installed (Node 18‑24, PostgreSQL/MySQL/SQLite). Enable the Revisionary plugin if you need versioned content. |
| Next.js | v15 with the app router (app/ directory). |
| Node | Same version range as Strapi. |
| Secret | A shared secret for HMAC verification (e.g., STRAPI_WEBHOOK_SECRET). |
| TypeScript | Project set up with tsconfig.json. |
1. configure a Strapi webhook
- In the Strapi admin, go to Settings → Webhooks and click Create new webhook.
- Set URL to the Next.js route you will create, for example
https://example.com/api/revalidate. - Choose the events you want to trigger ISR. Typical choices are:
entry.publishentry.updateentry.unpublishreview-workflows.updateEntryStage(to revalidate only after approval)
- Under Headers, add a custom header
X-Webhook-Secretwith the same secret you will use in Next.js. - Save the webhook. Strapi will now POST a JSON payload for each selected event.
2. create a secure Next.js route handler
Place the file at app/api/revalidate/route.ts. The handler reads the raw request body, verifies the HMAC signature, and calls the appropriate Next.js revalidation function.
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';
// The shared secret must match the one configured in Strapi
const WEBHOOK_SECRET = process.env.STRAPI_WEBHOOK_SECRET ?? '';
/**
* Verify the request came from Strapi.
* Strapi can be configured to send a SHA‑256 HMAC in the
* `X-Webhook-Signature` header. The HMAC is computed over the
* raw request body concatenated with a timestamp header.
*/
function verifySignature(req: NextRequest, rawBody: Buffer): boolean {
const signature = req.headers.get('x-webhook-signature');
const timestamp = req.headers.get('x-webhook-timestamp');
if (!signature || !timestamp) return false;
const hmac = crypto.createHmac('sha256', WEBHOOK_SECRET);
hmac.update(rawBody);
hmac.update(timestamp);
const expected = hmac.digest('hex');
// timingSafeEqual prevents timing attacks
return crypto.timingSafeEqual(Buffer.from(signature, 'hex'), Buffer.from(expected, 'hex'));
}
export async function POST(req: NextRequest) {
// Get raw body for signature verification
const rawBody = Buffer.from(await req.text());
if (!verifySignature(req, rawBody)) {
return new NextResponse('Invalid signature', { status: 401 });
}
// Parse the verified payload
const payload = JSON.parse(rawBody.toString());
const { event, entry } = payload as {
event: string;
entry: { documentId: string; slug?: string; locale?: string };
};
// Map Strapi events to Next.js revalidation calls
try {
switch (event) {
case 'entry.publish':
case 'entry.update': {
// Assuming your content type has a slug field
const path = `/${entry.slug ?? ''}`;
await revalidatePath(path);
// Optional tag for group invalidation (e.g., blog list)
await revalidateTag('blog');
break;
}
case 'entry.unpublish': {
// Revalidate the page so it can render a 404 or fallback
const path = `/${entry.slug ?? ''}`;
await revalidatePath(path);
break;
}
case 'review-workflows.updateEntryStage': {
// Only revalidate after the entry reaches the "approved" stage
if (payload.stage === 'approved') {
const path = `/${entry.slug ?? ''}`;
await revalidatePath(path);
}
break;
}
default:
// No action for other events
break;
}
return NextResponse.json({ revalidated: true });
} catch (err) {
console.error('Revalidation error:', err);
return new NextResponse('Revalidation failed', { status: 500 });
}
}Key points
revalidatePath(path)invalidates the static cache for a single route.revalidateTag(tag)invalidates all pages that were generated withcacheTag(tag)(useful for index pages).- The handler runs on the edge or serverless environment, matching Next.js 15's on‑demand ISR model.
3. using cache tags in your page components
When you render a list page (e.g., /blog), tag the data so that a single revalidateTag('blog') call clears the whole list.
// app/blog/page.tsx
import { cache, cacheTag } from 'react';
import { fetchBlogPosts } from '@/lib/api';
// Tag the cached response
export const fetchCachedPosts = cache(async () => {
cacheTag('blog'); // <-- all pages that use this tag share the cache
return await fetchBlogPosts();
});
export default async function BlogPage() {
const posts = await fetchCachedPosts();
return (
<section>
{posts.map(p => (
<article key={p.id}>
<h2>{p.title}</h2>
</article>
))}
</section>
);
}Now a single webhook event that calls revalidateTag('blog') forces the list page to regenerate.
4. handling content versioning and editorial workflows
Revisionary stores every version of an entry. The webhook payload includes documentId, which is stable across versions, and the current slug. To avoid revalidating drafts, filter events:
if (payload.event === 'entry.publish' && payload.entry?.documentId) {
// Only revalidate when the entry is published, not when a draft is saved.
const path = `/${payload.entry.slug}`;
await revalidatePath(path);
}If you use Review Workflows, listen for review-workflows.updateEntryStage and revalidate only when the stage becomes approved. This respects the editorial gate before the front‑end sees the change.
5. type‑safe integration with Strapi's OpenAPI typings
Strapi can generate TypeScript definitions for your content types (npm run strapi ts:generate-types). Import them in the Next.js project to get autocomplete and compile‑time safety.
import type { BlogPost } from '@/types/strapi';
export async function fetchBlogPosts(): Promise<BlogPost[]> {
const res = await fetch(`${process.env.STRAPI_URL}/api/blog-posts?populate=*`, {
headers: { Authorization: `Bearer ${process.env.STRAPI_TOKEN}` },
next: { revalidate: 0 }, // force server‑side fetch
});
const json = await res.json();
return json.data.map((d: any) => d.attributes as BlogPost);
}Using the generated types ensures the slug field exists and matches the route you revalidate.
6. testing the webhook locally
- Run Strapi and Next.js locally (e.g.,
npm run developfor Strapi,npm run devfor Next.js). - Install
ngrokor Vercel's dev server tunneling to expose a public HTTPS URL. - Update the Strapi webhook URL to the tunnel address.
- Trigger an event in Strapi (publish an article) and watch the Next.js console for
Revalidationlogs. - Verify the page was regenerated by checking the response headers (
x-nextjs-cacheshould beMISS).
7. CI/CD and observability
- CI – Add a step in your GitHub Actions workflow that runs
npm run strapi ts:generate-typesbefore building the Next.js app, guaranteeing the latest schema. - Deploy – Vercel automatically picks up the
revalidatePathcall; no extra build is required. - Monitoring – Log webhook processing results to a service like Logtail or Datadog. Include the
event,documentId, and outcome (revalidated / ignored). - Error alerts – Set up a webhook failure alert (e.g., Slack) if the route returns a non‑200 status.
8. common pitfalls and how to avoid them
| Symptom | Cause | Fix |
|---|---|---|
revalidatePath does nothing | The route handler returns before awaiting the call, or the path is missing a leading slash. | Ensure await revalidatePath('/my‑slug') and include the leading /. |
| 401 from Next.js | Signature verification fails because the secret differs or the timestamp header is missing. | Verify both Strapi and Next.js use the same STRAPI_WEBHOOK_SECRET and that the timestamp header is sent. |
| Stale list pages | You called revalidatePath for each article but not revalidateTag for the list. | Tag the list page with cacheTag('blog') and call revalidateTag('blog') in the webhook. |
| Drafts trigger ISR | Listening to entry.update fires on every draft save. | Limit to entry.publish or check payload.entry.publishedAt before revalidation. |
9. putting it all together
- Enable Revisionary to keep every version and use the
review-workflows.updateEntryStagewebhook for gated publishing. - Create the webhook in Strapi with the secret header.
- Add the route handler in Next.js (
app/api/revalidate/route.ts). - Tag your data with
cacheTagwhere appropriate. - Deploy and monitor the logs.
When done, any content change that passes the editorial review instantly invalidates the relevant static pages, delivering fresh content with the speed of static hosting.
For more details on Revisionary’s versioning and audit capabilities, see the Content API and the Review pages.
Sources
The Revisionary team
Developers who build Revisionary, a version history plugin for Strapi 5. We write about Strapi, web development, AI and application security.
This article was written with the help of AI.