Part 47: Embracing On-Demand Revalidation in Next.js

[Pages] Data Fetching

[Pages] Data Fetching

In our journey with Next.js, we've explored the benefits of Incremental Static Regeneration (ISR) by utilizing the revalidate option. This feature allows our pages to be regenerated after a specified timeout, ensuring that they fetch the latest data. However, ISR has its limitations—most notably, the delay in updating pages immediately after data changes in our CMS. Pages are only refreshed when the revalidation period expires and someone requests the page.

Fortunately, with the release of Next.js 12.2, a new feature called on-demand revalidation addresses these downsides. This feature allows us to regenerate pages as soon as data changes occur in the CMS, ensuring that our content is always up-to-date.

How On-Demand Revalidation Works

On-demand revalidation leverages API routes in Next.js, which can be triggered by our CMS whenever data is modified. This approach requires our CMS to support webhook functionality, allowing it to call our Next.js app and specify which page needs regeneration.

Setting Up a Webhook

Let's use a CMS like Strapi as an example:

  1. Create a Webhook: Navigate to the "Webhooks" section in the CMS settings and create a new webhook. Name it "Revalidate" (or any name you prefer). The URL should point to your Next.js application, typically http://localhost:3000/api/revalidate when running locally.

  2. Configure Events: Select events like "Entry Create", "Update", and "Delete" to trigger the webhook whenever a product is modified.

Implementing the API Route

Now, let's create the API route in our Next.js app to handle these webhook calls.

// pages/api/revalidate.js

export default async function handleRevalidate(req, res) {
  // Log the request body to see the data received from the CMS
  console.log('Webhook received:', req.body);

  // Extract relevant data from the request
  const { event, model, entry } = req.body;

  // Check if the event is related to products
  if (model === 'product') {
    const { id } = entry;

    try {
      // Revalidate both the home page and the specific product page
      await Promise.all([
        res.revalidate('/'),
        res.revalidate(`/products/${id}`)
      ]);

      console.log(`Revalidated product with id: ${id}`);
      res.status(204).end(); // Respond with No Content
    } catch (err) {
      res.status(500).json({ error: 'Failed to revalidate' });
    }
  } else {
    res.status(204).end(); // No action needed if not a product
  }
}

Explanation

  • Request Handling: The API route listens for POST requests from the CMS, logging the request body to understand what data is received.

  • Conditional Logic: We check if the event pertains to a product. If so, we extract the product ID.

  • Revalidation: Using res.revalidate, we trigger regeneration for both the home page and the specific product page. This is done asynchronously and in parallel using Promise.all.

  • Response: A 204 status code indicates success, as the CMS only requires acknowledgment of the request.

Testing On-Demand Revalidation

  1. Run in Development: Start your Next.js app in development mode to test the API route.

  2. Modify Data: Change a product in the CMS to trigger the webhook.

  3. Check Logs: Observe the Next.js server logs to verify that revalidation occurs.

Advantages of On-Demand Revalidation

  • Immediate Updates: Pages reflect changes instantly, enhancing the user experience by eliminating delays.

  • Efficiency: Only the necessary pages are revalidated, optimizing resource usage.

  • Parallel Processing: Revalidation tasks are executed concurrently, reducing the overall time required.

Conclusion

On-demand revalidation significantly improves how we manage content updates in Next.js applications. By leveraging webhooks and API routes, we ensure our pages remain current without waiting for revalidation intervals. This feature is highly recommended for any Next.js project utilizing a CMS with webhook support. As Next.js continues to evolve, features like on-demand revalidation empower developers to create dynamic, responsive web applications with ease.

Last updated