Cachebust when publishing

Please fill out as many of the following questions as possible so we can help you promptly! If you don’t know how to answer or it does not apply, feel free to remove it or leave it blank.

Builder content link

Builder public api key
1d8ecee591ac4358befb8fe998100548

What are you trying to accomplish

  • I am exploring ways to perform cachebust only when page is published, because this would decease our build time on Vercel. By directing enabling cachebust, during the build time, Vercel would generate all the static pages.
  • in NextJs, there is a way to skip static page generation during build (see docs), but this approach does not seem to work with Builder SDK.

Code stack you are integrating Builder with
NextJs

:pray:

Hello @tlee-pb,

To dynamically cachebust with Builder only when a page is published, you can leverage Builder’s webhooks along with your Next.js setup. Here’s how you can set it up:

Step 1: Set Up the Webhook in Builder

  1. Create a Webhook in Builder:

    • Go to your Builder.io space.
    • Navigate to Settings > Webhooks.
    • Add a new webhook that will be triggered on publish. This ensures the webhook fires every time content is published.
  2. Webhook Configuration:

    • Configure the webhook URL to point to an API endpoint in your Next.js application.
    • Example webhook payload can be found in your uploaded documents.

Step 2: Create a Webhook Handler in Next.js

  1. Create an API route: pages/api/webhook.js
    • This API route will handle incoming webhook requests from Builder.io.
// pages/api/webhook.js
export default async function handler(req, res) {
  if (req.method === 'POST') {
    const { newValue, previousValue } = req.body;
    
    if (newValue && newValue.published === 'published') {
      // This signifies that a page has been published
      await res.revalidate('/');
    }

    return res.status(200).json({ message: 'Webhook received and processed' });
  } else {
    res.setHeader('Allow', ['POST']);
    return res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}

Step 3: Modify Your Next.js Configuration

  1. Configure revalidation:
    • This ensures that your pages are revalidated and the cache is invalidated when the webhook is called.
// next.config.js
module.exports = {
  async redirects() {
    const { builder } = require('@builder.io/sdk');

    return builder
      .getAll('url-redirects', {
        apiKey: 'YOUR_API_KEY',
        options: { noTargeting: true },
        cachebust: true,
      })
      .then(results => results
        .filter(content => {
          const data = (content || {}).data || {};
          return !!(data.sourceUrl && data.destinationUrl);
        })
        .map(({ data }) => ({
          source: data.sourceUrl,
          destination: data.destinationUrl,
          permanent: !!data.redirectToPermanent,
        })), (error) => {
          console.error("Error setting up redirects", error);
          return [];
        },
      );
  },
}
  1. ** Scheduling and Cachebusing when using Webhooks**:
    • When your webhook triggers on publish, the provided handler will call res.revalidate() on the path(s) that need to be updated.

By following these steps, you create an efficient cachebusting mechanism that triggers only on publication, avoiding unnecessary rebuilds and optimizing your build times on Vercel. For more detailed information, visit the respective cachebust documentation and webhooks documentation on Builder.io.

Hello Manish,

Thank you for the prompt reply.
The Cachebust doc appears to be broken.

Thanks.

Hello @tlee-pb,

For cachebust, you can refer to the below links

let response = fetch('https://cdn.builder.io/api/v1/html/DOC_ID?apiKey=YOUR_KEY&cachebust=true')
// Now you can save and later serve the HTML as you please
let html = response.data.html