Using Vercel Cron Jobs

In a recent project of mine, i needed a code piece to run in every 15 days to update some file contents. Now there are multiple ways to do this, node cron is one of them and very popular. But I have heard about Vercel's cron jobs and wanted to try it out. It turned out to be very easy to use and I thought I should write about it for others to know. Please note this is not a tutorial on how to use cron jobs, but how to use Vercel's cron jobs. Also you should know next.js basics and how to deploy a next.js project to Vercel.

Started from their official cron job documentation, it was pretty straight forward. If you are familiar with next.js api routes, you will feel right at home. You just need to create a file in api folder and export a function from it. That function will be called by Vercel's cron job scheduler, like you will call any other api route.

Let's create a file named refreshdata.js in api folder and export a function from it.

export default async function handler(req, res) {
  res.status(200).json({ message: "Hello from cron job" });
}

Now create(if it doesn't exists already) a vercel.json file in the root of your project and add the following code to it.

{
  {
  "crons": [
    {
      "path": "/api/refreshdata",
      "schedule": "0 0 15 * *"
    }
  ]
}

Remember the the name in the path is your api route so it should match with the file name. Above is supposed to run in 15th of every month. To test it, just call the api as you normally would. You can use curl or postman or any other tool you like. I use thunder client in vscode.

Please note you can have multiple cron jobs in the same file. Just add them to the array.

{
  {
  "crons": [
    {
      "path": "/api/refreshdata",
      "schedule": "0 0 15 * *"
    },
    {
      "path": "/api/sendemails",
      "schedule": "0 0 15 * *"
    }
  ]
}

Now you can deploy your project and the cron job will be scheduled. You can check the logs in the vercel dashboard. Also make sure the cron job setting is enabled in the project settings. It mostly enabled by default.

Vercel cron job dashboard

And that's it. You can use this to schedule any task you want. You can use it to send emails, update database, or anything you want. Just make sure the task is not too long to complete. Vercel has a timeout of 10 seconds for cron jobs in free tier atleast. Also it's free to use while in beta, their docs say it will be paid after beta.

I hope you find this useful. Thanks for reading. See you in the next one.