Tutorial
4 min read

Cron Jobs Quickstart

Learn how to schedule cron jobs to run at specific times or intervals.
Table of Contents

Cron Jobs are available on all plans

The following guide will show you how to create a cron job on Vercel that executes every day at 5 am UTC.

  1. Begin by creating a Serverless or Edge Function for your project. The function will echo the current time using the World Time API.

    Next.js (/app)
    Next.js (/pages)
    Other frameworks
    app/api/cron/route.ts
    export async function GET() {
      const result = await fetch(
        'http://worldtimeapi.org/api/timezone/America/Chicago',
        {
          cache: 'no-store',
        },
      );
      const data = await result.json();
     
      return Response.json({ datetime: data.datetime });
    }

    For those using TypeScript versions below 5.2, it's important to adapt the code to import NextResponse from 'next/server' and use NextResponse.json for the response. This ensures compatibility with earlier TypeScript versions in Next.js applications. In TypeScript 5.2 and above, the standard new Response pattern should be used.

  2. Create or go to your vercel.json file and add the following code:

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

    The crons property is an array of cron jobs. Each cron job has two properties:

    • The path, which must start with /
    • The schedule property, which must be a string that represents a cron expression. In this example, the job is scheduled to execute every day at 5:00 am UTC
  3. When you deploy your project, Vercel's build process creates the cron job. Vercel invokes cron jobs only for production deployments and not for preview deployments

    You can also deploy to your production domain using the CLI:

    terminal
    vercel deploy --prod

Your cron job is now active and will call the /api/cron path every day at 5:00 am UTC.

Last updated on April 30, 2024