Skip to content

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

a close up of a piece of paper with arrows
Photo by Joachim Schnürle on Unsplash

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

RequirementDetails
Strapiv5 installed (Node 18‑24, PostgreSQL/MySQL/SQLite). Enable the Revisionary plugin if you need versioned content.
Next.jsv15 with the app router (app/ directory).
NodeSame version range as Strapi.
SecretA shared secret for HMAC verification (e.g., STRAPI_WEBHOOK_SECRET).
TypeScriptProject set up with tsconfig.json.

1. configure a Strapi webhook

  1. In the Strapi admin, go to Settings → Webhooks and click Create new webhook.
  2. Set URL to the Next.js route you will create, for example https://example.com/api/revalidate.
  3. Choose the events you want to trigger ISR. Typical choices are:
    • entry.publish
    • entry.update
    • entry.unpublish
    • review-workflows.updateEntryStage (to revalidate only after approval)
  4. Under Headers, add a custom header X-Webhook-Secret with the same secret you will use in Next.js.
  5. 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.

ts
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 with cacheTag(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.

tsx
// 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.

A blue glass cloud icon with data layers above a silver padlock
Photo by Growtika on Unsplash

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:

ts
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.

ts
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

  1. Run Strapi and Next.js locally (e.g., npm run develop for Strapi, npm run dev for Next.js).
  2. Install ngrok or Vercel's dev server tunneling to expose a public HTTPS URL.
  3. Update the Strapi webhook URL to the tunnel address.
  4. Trigger an event in Strapi (publish an article) and watch the Next.js console for Revalidation logs.
  5. Verify the page was regenerated by checking the response headers (x-nextjs-cache should be MISS).

7. CI/CD and observability

  • CI – Add a step in your GitHub Actions workflow that runs npm run strapi ts:generate-types before building the Next.js app, guaranteeing the latest schema.
  • Deploy – Vercel automatically picks up the revalidatePath call; 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

SymptomCauseFix
revalidatePath does nothingThe 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.jsSignature 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 pagesYou 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 ISRListening to entry.update fires on every draft save.Limit to entry.publish or check payload.entry.publishedAt before revalidation.

9. putting it all together

  1. Enable Revisionary to keep every version and use the review-workflows.updateEntryStage webhook for gated publishing.
  2. Create the webhook in Strapi with the secret header.
  3. Add the route handler in Next.js (app/api/revalidate/route.ts).
  4. Tag your data with cacheTag where appropriate.
  5. 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.

TagsNext.jsStrapiISRwebhooksTypeScriptcontent versioning

Sources

  1. Next.js 15 API reference – revalidatePath
  2. Next.js 15 API reference – revalidateTag
  3. Next.js 15 guide – Incremental Static Regeneration
  4. Strapi documentation – Webhooks
  5. Strapi blog – Incremental static regeneration in Next.js with Strapi
  6. Terry Hunt – Strapi webhooks + Next.js revalidation tutorial

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.

All articles

Development

Distributed tracing for Strapi 5 and Next.js

Connect Next.js and Strapi 5 with OpenTelemetry distributed tracing. Learn how to propagate trace context, instrument Koa and Knex, and isolate latency.

· 5 min read