Vercel cron jobs
Beta announcement
Last week, Vercel announced beta availability of their cron jobs. They allow you to schedule a serverless function to run on a regular basis. This allows you to run tasks on a fixed schedule, defined by a cron expression. For this example I'll be using a cron job to do a daily deploy of my blog.
Image: Vercel announcement on Twitter
Setting up the cron job
For this example I'll be using Svelte.
First we need to create an API endpoint, located at routes/API/cron/+server.ts
.
Any endpoint location will do, as long as it's callable via a GET request.
At the root of our project, we also want to create a vercel.json configuration file. We can use this json file to configure a multitude of things, including our cron jobs.
This json file contains an array of cron configurations, containing a path and a schedule. The path refers to the relative URL at which our endpoint is available. The schedule is a cron expression , which defines when the endpoint should be called.
Note
While in beta, cron jobs are limited to a minimum of one execution a day for the hobby plan. I assume this is subject to change, but we'll see.
Running the cron job
Localhost
To locally test the behavior of this cron job, we can just test it in the same way we would test any other endpoint.
I use Postman for this, but you can also use curl or any other tool.
For the example above, the endpoint lives at localhost:5173/api/cron.
A simple GET request to this endpoint will trigger the cron job.
Manually invoking the cron job from the Vercel dashboard
When deployed to the production environment, we can manually invoke the cron job from the Vercel dashboard.
Image: Each project now has a tab with cron job information
We can access the cron job information through the cron tab on each project. It gives us an overview of the available cron jobs, as well as the possibility to manually invoke them. The logging output of the cron job is also available here, but only when the tab is open as no logging information is retained by default. It's possible to add a log sink however, to create a permanent log of the cron job output.
Adding in the deployment url
At this point our cron function doesn't do anything yet, as our required environment variable VERCEL_HOOK
is not set.
For our local development environment, we can just set this variable in our .env file.
For the production environment, we can set this variable in the Vercel dashboard through the project settings.
And there we have it! With this cron job we have a daily deployment of our blogging site at 5 in the morning. Vercel cron jobs allow for a really easy and frictionless way of setting up cron jobs, all maintained in the same codebase as the main website. I like it!