Docs

CRON

Getting Started with Rescale CRON Next.js package

Motivation

CRON is a package that provides a simple way to schedule tasks in Next.js applications using Vercel cron. The main goal of this package is to improve code DX.

Installation

Terminal
npm install @rescale/cron

Usage

To make an CRON endpoint using @rescale/cron package, first of all you need to create an API route in your Next.js application. Then, you can use the CronJob function to schedule tasks.

Create API route endpoint

app/api/cron/daily/route.ts
import type { NextRequest, NextResponse } from 'next/server';
import { CronJob } from '@rescale/cron'; 
// [...] other imports
 
export async function GET(
  request: NextRequest,
) {
  return CronJob(request, [ 
    updateSubscriptions(), 
    sendNewsletter(), 
  ]); 
}

Configure Vercel cron

vercel.json
{
  "crons": [
    {
      "path": "/api/cron/daily", 
      "schedule": "0 0 * * *"
    }
  ]
}

To secure your cron jobs from public traffic, set the environment variable CRON_SECRET. Our package will detect it and use it to protect any cron job from public traffic.

You can generate secure secrets using the following command:

Terminal
openssl rand -base64 32

Deploy your project

Deploy your project to Vercel. After deploying, you can check the logs to see if the cron job is running successfully.

Warning

Vercel cron functions runs only on production environments. If you want to test it on preview/local, you need to use Postman or HTTPie client and make an GET call to /api/cron/daily endpoint with Authorization header that includes CRON_SECRET value.

Last updated on

On this page