Firebase Code not works on vercel, but works everywhere

export const dynamic = "force-dynamic"
import type { NextRequest } from 'next/server';
import { adminDb } from '@/src/lib/firebase/admin';
import { getFirestore, QuerySnapshot } from 'firebase-admin/firestore';
 
export function GET(request: NextRequest) {
  console.log('πŸ€– Cron job started:', new Date().toISOString());
  
  const authHeader = request.headers.get('authorization');
//   if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {
//     return new Response('Unauthorized', {
//       status: 401,
//     });
//   } 

  checkAndCompleteExpiredTasks();
  console.log('βœ… Cron job completed:', new Date().toISOString());
  return Response.json({ success: true });
}

async function checkAndCompleteExpiredTasks() {
  try {
    const now = new Date().toISOString();
    console.log('πŸ“… Checking for expired tasks at:', now);
    
    const tasksRef = adminDb.collection('agent_tasks');
    console.log('πŸ“š Collection reference created');
    let snapshot;
    try {
        snapshot = await tasksRef.where('status', '==', 'created').get();
        console.log("Query executed, snapshot size:", snapshot.size);
      } catch (error) {
        console.error('Error fetching tasks:', error);
      }
    console.log("Query executed, snapshot size:", snapshot?.size)
    
    let expiredTasks: Object[] = [];
    snapshot?.forEach(doc => {
        const data = doc.data();
        if (data.taskFinishTime <= now) {
            expiredTasks.push({
                id: doc.id,
                ...data
            });
            console.log("Found expired task:", doc.id);
        }
    })

    console.log("πŸ” Found", expiredTasks.length, "expired tasks");
    if (expiredTasks.length > 0) {
        const completionPromises = expiredTasks.map(async (task: any) => {
            const taskId = task.id;
            console.log(`⚑ Processing task ${taskId}`);
            
            try {
            const response = await fetch(
                `${process.env.NEXT_PUBLIC_APP_URL}/api/agents/tasks/${taskId}/complete`,
                {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    // Add any necessary authentication headers
                }
                }
            );

            if (!response.ok) {
                console.error(`❌ Failed to complete task ${taskId}: ${response.statusText}`);
                throw new Error(`Failed to complete task ${taskId}: ${response.statusText}`);
            }

            console.log(`βœ… Successfully completed task ${taskId}`);
            } catch (error) {
            console.error(`❌ Error completing task ${taskId}:`, error);
            }
        });
    }
    console.log('🏁 Finished processing all expired tasks');
    
  } catch (error) {
    console.error('πŸ’₯ Detailed error in checkAndCompleteExpiredTasks:', {
      message: (error as Error).message,
      code: (error as any).code,
      stack: (error as Error).stack
    });
    throw error;
  }
}

This code i use in nextjs and it’s accessible at /api/cron

I have this code, and it works everywhere fins, but not on Vercel. There is no any error, code just stopping execution seems on query to firebase.

Last console log message i see: console.log('πŸ“š Collection reference created');

And this code does not work because I don’t see the next log.

const snapshot = await tasksRef
        .where('status', '==', 'created')
        .get()

On all other routes, even in Vercel, Firebase works fine.

logs

:robot: Cron job started: 2024-12-17T15:11:14.441Z
:date: Checking for expired tasks at: 2024-12-17T15:11:14.442Z
:books: Collection reference created
:white_check_mark: Cron job completed: 2024-12-17T15:11:14.458Z

Hey @15august. I cleaned up your post to make the code easier to read. Please let me know if I got any of it wrong.

Is the cron job the only thing that fails? Or does the function at /api/cron fail when you run it directly?

no, cron itself works , but the function behind the endpoint /api/cron - fails on the place where it’s time to read from DB

still having this issue, works absolutely randomly we already have a customers, but still this sometime works sometimes no, but locally and on normal server works perfectly

Does the database request time out? You should be able to see in the runtime logs how long the function ran. If the number reaches our slightly exceeds the current maximum duration limit for Vercel Functions in your project, that might be why it succeeds only some of the time. There could be a similar limit on the database side which would cause the same problem.