# Part 72: Enhancing Data Freshness with On-Demand Revalidation in Next.js

<figure><img src="https://159896965-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3LclXKUpANLoSt8DPdYV%2Fuploads%2FJK8G3Yjm1qHwjGSqwUcV%2F1675674296261.jpeg?alt=media&#x26;token=989182c4-9098-4bba-8dd9-52aeb4b0f941" alt=""><figcaption><p>[App] Dynamic Rendering and Revalidation</p></figcaption></figure>

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:

1. **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.
2. **Staggered Updates**: Different pages may update at slightly different times, leading to inconsistencies if multiple pages rely on the same data.
3. **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

1. **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

2. **Go to Settings**: Once you're logged in, find and click on the "Settings" section in the left sidebar of the admin panel.
3. **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

4. **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

5. **Name the Webhook**: Enter a name for your webhook. This is for your reference, so make it descriptive of its purpose.
6. **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.
7. **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.
8. **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

9. **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.
10. **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

11. **Save Changes**: Once you have configured the webhook to your liking, click the "Save" button to apply the changes.

<figure><img src="https://159896965-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3LclXKUpANLoSt8DPdYV%2Fuploads%2FXYnVb4x2dEo6k6vIymRh%2Fimage.png?alt=media&#x26;token=a9fe862c-25f8-49ec-adde-bbb48793022a" alt=""><figcaption></figcaption></figure>

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

1. **Define the Route**: Create a new route in the `app` folder. Unlike traditional page routes, this will use a `route.js` file.

   ```javascript
   // 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 });
   }
   ```
2. **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.
3. **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:

1. **Start the Development Server**: Ensure your Next.js server is running.
2. **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:

1. **React to CMS Changes**: Modify the route handler to react to specific changes in the CMS data.
2. **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.
