Next.js

Schedule / Cron Jobs

Setting up scheduled tasks (cron jobs) using Vercel Cron and Next.js API Routes.

Vercel Configuration: Defining the cron schedule in your project configuration.
📄vercel.json
JSON
{
  "crons": [
    {
      "path": "/api/cron",
      "schedule": "0 10 * * *"
    }
  ]
}
Cron Handler: The API route that executes the scheduled task.
📄app/api/cron/route.ts
TypeScript
import { NextResponse } from 'next/server';

export async function GET(request: Request) {
  // Security check: ensure the request is triggered by Vercel Cron
  const authHeader = request.headers.get('authorization');
  if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {
    return new Response('Unauthorized', {
      status: 401,
    });
  }

  try {
    // Perform your scheduled task (e.g., database cleanup, sending emails)
    console.log('Running daily task at 10 AM');
    
    // await db.logs.deleteMany({ where: { createdAt: { lt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) } } });

    return NextResponse.json({ success: true, message: 'Cron job executed successfully' });
  } catch (error) {
    return NextResponse.json({ success: false, error: 'Internal Server Error' }, { status: 500 });
  }
}