Search code examples
reactjsnext.jscronvercel

Vercel Cron Job not firing with Next 13 Route API


I am using Next 13 app dir.

I have a route.ts file:

app/api/cron/set-completed-goals/route.ts
import { prisma } from '@/lib/prisma';
import { NextResponse } from 'next/server';
export async function GET() {
  const users = await prisma.user.findMany();

  for (const user of users) {
    const goals = await prisma.goal.findMany({
      where: { userId: user.id },
    });

    for (const goal of goals) {
      if (goal?.percentage ?? 0 >= 100) {
        await prisma.$transaction([
          prisma.user.update({
            where: { id: user.id },
            data: {
              completedGoals: [...user.completedGoals, goal.id],
            },
          }),
          prisma.goal.update({
            where: { id: goal.id },
            data: { percentage: 0 },
          }),
        ]);
      }
    }
  }
  return NextResponse.json({ message: 'Completed goals updated' });
}

And a vercel.json:

{
  "crons": [
    {
      "path": "/api/cron/set-completed-goals",
      "schedule": "0 0 * * *"
    }
  ]
}

When I fire the function in my localhost manually it works as intended.

However when I manually fire the cron job on vercel, I see in the logs:

200
[GET] /api/cron/set-completed-goals

It seems to be returning a 200, but nothing is actually changing in my database.

I am new to cron jobs, and it's not obvious what is wrong.

Any help is greatly appreciated.


Solution

  • It started to work now.

    I believe it wasnt working properly because of Vercel limitations for Hobby plans, and somehow went over my usage.

    https://vercel.com/blog/cron-jobs#limits-of-cron-jobs-and-vercel-functions

    Wish they had better logs or some sort of limit usage view to reflect what goes on, but it is what it is.