Vercel Cron Jobs
Vercel Cron Jobsβ require simple authorization using an environment variable. This can be achieved by creating a decorator that checks authorization header with a secret key.
src/decorators/cronGuard.ts
import { HttpException, HttpStatus, createDecorator } from 'vovk';
const cronGuard = createDecorator(async (req, next) => {
if (req.headers.get('authorization') !== `Bearer ${process.env.CRON_SECRET}`) {
throw new HttpException(HttpStatus.UNAUTHORIZED, 'Unauthorized');
}
return next();
});
export default cronGuard;
Apply the cronGuard
decorator to the controller method that should be protected by the cron job authorization.
src/modules/cron/CronController.ts
import { get, prefix } from 'vovk';
import cronGuard from '../decorators/cronGuard';
@prefix('cron')
export default class CronController {
@get('do-something')
@cronGuard()
static async doSomething() {
// ...
}
}
Add the cron job to the vercel.json
file. The schedule
field uses the cron syntax (at this case the cron job will run every day at midnight).
/vercel.json
{
"crons": [
{
"path": "/api/cron/do-something",
"schedule": "0 0 * * *"
}
]
}
Last updated on