~/techulus

Thoughts, experiments and ideas.

Authenticating Vercel Cron Jobs

// Written by Arjun Komath

// Sat, Feb 10 2024

Vercel Cron Jobs are a powerful tool for automating repetitive tasks. By using cron expressions, you can schedule tasks to run automatically at specific intervals. However, securing these cron jobs is crucial to ensure that they can’t be run by just anyone with the known route.

Here’s a step-by-step guide on how to authenticate Vercel Cron Jobs:

import { NextRequest, NextResponse } from 'next/server'

export async function GET(req: NextRequest) {
  // get the bearer token from the header
  const authToken = (req.headers.get('authorization') || '')
    .split('Bearer ')
    .at(1)

  // if not found OR the bearer token does NOT equal the CRON_SECRET
  if (!authToken || authToken != process.env.CRON_SECRET) {
    return NextResponse.json(
      { error: 'Unauthorized' },
      { status: 401 }
    )
  }

  // if token exists then move on with the cron job ...
}

By following these steps, you can ensure that only Vercel can run the cron job from their servers.