Part 72: Enhancing Data Freshness with On-Demand Revalidation in Next.js
[App] Dynamic Rendering and Revalidation

Keeping your website updated with the latest content is crucial, especially for dynamic sites that rely on data from a Content Management System (CMS). While time-based revalidation in Next.js is a popular approach, it has its limitations. This blog post explores an advanced method called On-Demand Revalidation, which provides more control over when your pages update.
The Limitations of Time-Based Revalidation
Time-based revalidation updates pages at predetermined intervals, which can lead to a few drawbacks:
Delayed Updates: Changes in the CMS are not immediately reflected on the website. The update appears only after the specified interval, which can be seconds or even minutes later.
Staggered Updates: Different pages may update at slightly different times, leading to inconsistencies if multiple pages rely on the same data.
Unnecessary Regeneration: The server regenerates pages periodically, even if the underlying data hasn't changed, which can be inefficient.
Introducing On-Demand Revalidation
On-Demand Revalidation in Next.js allows for explicit control over page updates. This approach enables you to revalidate pages or API requests based on specific triggers rather than fixed time intervals. The core idea is to notify your application when data changes, prompting it to update relevant pages immediately.
Setting Up On-Demand Revalidation
To implement this feature, we need a mechanism to detect changes in the CMS and notify the Next.js application. Typically, this is achieved using webhooks.
Creating webhooks in Strapi is a straightforward process that allows you to trigger actions in response to specific events, such as content creation or updates. Here’s a step-by-step guide to setting up webhooks in Strapi:
Step 1: Access the Strapi Admin Panel
Log into Strapi: Open your web browser and navigate to your Strapi instance's admin panel. Log in with your credentials.
Step 2: Navigate to the Webhooks Section
Go to Settings: Once you're logged in, find and click on the "Settings" section in the left sidebar of the admin panel.
Select Webhooks: In the settings menu, look for the "Webhooks" option and click on it. This will take you to the webhooks management page.
Step 3: Create a New Webhook
Add a New Webhook: On the webhooks page, you should see an option to "Add new webhook." Click this button to start creating a new webhook.
Step 4: Configure the Webhook
Name the Webhook: Enter a name for your webhook. This is for your reference, so make it descriptive of its purpose.
Enter the URL: Provide the URL of the endpoint where the webhook payloads will be sent. This should be the URL of the external service that will handle the webhook.
Select Events: Choose the events that will trigger the webhook. Strapi offers a variety of events such as "Entry Create," "Entry Update," "Entry Delete," etc. Select the ones relevant to your use case.
Custom Headers (Optional): If your webhook endpoint requires specific headers (like authentication tokens), you can add them in the "Headers" section.
Step 5: Test the Webhook
Enable the Webhook: Ensure that the webhook is enabled by toggling the switch. This will activate the webhook so it can start listening for events.
Test the Setup: To make sure everything is configured correctly, you might want to test the webhook. This can be done by triggering one of the selected events in your Strapi application and verifying that the payload is received at the specified endpoint.
Step 6: Save the Webhook
Save Changes: Once you have configured the webhook to your liking, click the "Save" button to apply the changes.

Creating a Route Handler
A Route Handler in Next.js provides a way to handle different HTTP requests without returning a traditional web page. Instead, it can return data like JSON. Let's create a simple API route that can be triggered by webhooks.
Define the Route: Create a new route in the
appfolder. Unlike traditional page routes, this will use aroute.jsfile.// app/webhooks/cms-event/route.js export async function POST(request) { const payload = await request.json(); console.log('payload:', payload); return new Response(null, { status: 204 }); }Handle Webhook Requests: This route listens for POST requests from the CMS. When a change occurs, the CMS sends an HTTP request with data about the change.
Log the Payload: For now, we're logging the payload to verify that the webhook is functioning correctly. The response status is set to 204, indicating a successful processing with no content return.
Testing the Route Handler
To test the setup:
Start the Development Server: Ensure your Next.js server is running.
Trigger the Webhook: Use your CMS to send a test request to the webhook URL. Check your server logs to see the payload, confirming that the route is working.
Implementing On-Demand Revalidation
Once the webhook is set up and verified, you can implement On-Demand Revalidation:
React to CMS Changes: Modify the route handler to react to specific changes in the CMS data.
Revalidate Pages: Use Next.js functions to revalidate pages or data fetches tagged with specific identifiers, ensuring they update immediately after receiving a webhook notification.
Benefits of On-Demand Revalidation
Immediate Updates: Reflect changes on your website as soon as they occur, enhancing user experience and data accuracy.
Efficient Resource Usage: Only regenerate pages when necessary, reducing server load and optimizing performance.
On-Demand Revalidation offers a powerful way to manage data freshness in Next.js applications, overcoming the limitations of time-based intervals. By using webhooks and route handlers, you can ensure that your site always displays the most up-to-date information. In future discussions, we'll delve deeper into integrating this with real CMS changes and automating the revalidation process.
Last updated