Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

What is wrong and how to resolve it?

like image 429
ozansozuoz Avatar asked Oct 16 '25 19:10

ozansozuoz


1 Answers

I faced the same issue but i did solve it with this code.

export const revalidate = 0
export async function GET(req: Request) {
    // your db logic
    return NextResponse.json({
        result:result
    });
}

I hope this code will help you...

like image 143
dancingball Avatar answered Oct 19 '25 13:10

dancingball