Go Back

Triggering a Vercel build via cron

Posted: 

Using WordPress.com as a headless CMS, I looked into the possibility of triggering a Vercel build every time I publish or update a post. This is possible, and I think I’ll still write a blog about it, but I’d rather have blogs published on a schedule. I’m thinking to have them available Monday morning. This requires some kind of cron job.

Vercel now offers cron jobs through a serverless function. You setup the cron in your vercel.json file and then the code to execute in the serverless function.

Vercel webhook to build and deploy site

First we need to setup the webhook we will call in order to re-deploy the site with Vercel.

In our Vercel project dashboard we navigate to Settings > Git > Deploy Hooks. We need to give it a unique identifier that will appear as the url. I called mine monday deploys. It will return a unique URL. Be sure to keep this secret otherwise anyone will be able to trigger your build.

Setup a cron task to hit the deploy webhook

Setup an env variable that will hold your deploy hook.

Create a new file in your NextJS api folder and call is something like cron.ts.

export default async function handler() {
  if (!process.env.MONDAY_DEPLOY_URL) {
    throw new Error(
      "You must define MONDAY_DEPLOY_URL env variable for this cron."
    );
  }
  return await fetch(process.env.MONDAY_DEPLOY_URL);
}

All this does is hit the deploy URL with a GET request.

In our vercel.json file we will define our cron. Mine is set to build every Monday morning at 8am.

{
  "crons": [
    {
      "path": "/api/cron",
      "schedule": "0 8 * * 1"
    }
  ]
}

That’s it. Now I can schedule my posts within WordPress.com knowing that anything published there will go live Monday mornings.