Vercel has finally dropped Cron jobs for your application. This means you can run those jobs hourly, daily, monthly, or you can even run them right away.
So let's look at how this is implemented with the Next.js application, and let's talk about why this is beneficial to everybody in the ecosystem.
Implementing a Cron Job
To implement a Cron Job, you need to create a new file in the pages/api
directory. This file will be a serverless function, and it will be triggered by the Cron Job.
// api/cron.js
export default (req, res) => {
res.status(200).json({ message: 'Hello World' });
};
This is a very simple function that will return a JSON response with the message Hello World
.
Scheduling a Cron Job
To schedule a Cron Job, you need to create a vercel.json
file in the root of your project. This file will contain the configuration for your Cron Job.
// vercel.json
{
"crons":[
{
"path": "/api/cron",
"schedule": "0 0 * * *"
}
]
}
This will schedule a Cron Job to run every day at midnight. You can use any cron syntax to schedule your Cron Job.
Why is this good?
One of the biggest issues I have run into in the past is if I need a Cron job, I've had to go and set it up somewhere else, like Render or one of the third party integrations that Vercel has.
Then if I ever want to run the Cron job on a one off, I have to log into another third party system and then try it out. But what's great about this is the API route is still valid regardless.
So if you have a Cron job that runs every day and you need to kick off a single run, you can just hit the end point with whatever you might need.
Limitations
The are some limitations to cron jobs for example on the hobby plan you can only run a cron job every day or more.