Search code examples
typescriptfirebasefirebase-realtime-databasevercelproduction

Firebase Realtime Database Requests Timing Out on Vercel Deployment But Working Locally


I'm encountering an issue when trying to send requests to my Firebase Realtime Database from a Vercel-deployed application. The same requests work perfectly fine in my local development environment, both in development and production modes. However, once deployed on Vercel, I consistently receive timeouts and Firebase warnings.

Example of the Code That's Failing:

Here's a minimal, reproducible example of the serverless function that fails when deployed on Vercel:

import { NextRequest, NextResponse } from 'next/server';
import { adminDb } from '@/lib';
import { env } from '@/lib';

const headers = {
  "Access-Control-Allow-Origin": env.CORS_ORIGIN,
  "Access-Control-Allow-Methods": "GET, OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type, Authorization",
};

export async function OPTIONS(request: NextRequest) {
  return new Response(null, {
    status: 204,
    headers,
  });
}

export async function GET(request: NextRequest, context: { params: { tab: string, nameOrId: string } }) {
  if (!adminDb) {
    return NextResponse.json(
      {
        error: "Service Unavailable",
        result: "fail",
        message: "Firebase services are not available",
      },
      {
        status: 503,
        headers: headers,
      }
    );
  }

  const { tab, nameOrId } = context.params;
  const refPath = `info/${tab}/${nameOrId}`;
  const infoRef = adminDb.ref(refPath);
  const snapshot = await infoRef.get();

  if (snapshot.exists()) {
    const info = snapshot.val();
    return NextResponse.json({ success: true, info }, { status: 200, headers });
  }

  return NextResponse.json({ error: "Info not found" }, { status: 404, headers });
}

Observations:

  • Firebase Realtime Database is throwing warnings, but the message is {}.
  • Multiple 504 Gateway Timeout errors are being returned by Vercel, indicating that the serverless function is not completing within the 10-second limit.

Logs from Vercel:

Aug 30 12:25:46.97
GET
---
bsb-backend.vercel.app
/api/public/images/slideshow
[2024-08-30T10:25:46.973Z] @firebase/database: FIREBASE WARNING: {}

Aug 30 12:25:46.52
GET
---
bsb-backend.vercel.app
/api/public/images/footer
[2024-08-30T10:25:46.526Z] @firebase/database: FIREBASE WARNING: {}

Aug 30 12:25:47.07
GET
---
bsb-backend.vercel.app
/api/public/images/footer
Vercel Runtime Timeout Error: Task timed out after 10 seconds

Aug 30 12:25:37.08
GET
504
bsb-backend.vercel.app
/api/public/info/mottos
[GET] /api/public/info/mottos?nxtPtab=mottos status=504

Steps I've Taken:

  • Verified that my internet connection is stable.
  • Checked that the database is nearly empty, so size or latency shouldn't be an issue.
  • I'm using Firebase Admin SDK to interact with Firebase services.

Firebase Initialization Code:

Here’s a shorter version of the Firebase initialization code I’m using in my project:

import * as admin from 'firebase-admin';

if (!admin.apps.length) {
  admin.initializeApp({
    credential: admin.credential.cert({
      projectId: process.env.FIREBASE_PROJECT_ID,
      clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
      privateKey: process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, '\n'),
    }),
    databaseURL: process.env.FIREBASE_DATABASE_URL,
  });
}

const adminDb = admin.database();
const adminAuth = admin.auth();
const adminStorage = admin.storage();

export { admin, adminDb, adminAuth, adminStorage };

Context:

  • Deployment Platform: Vercel
  • Database: Firebase Realtime Database, with correct credentials and configurations.
  • SDK: Using Firebase Admin SDK in serverless functions.

Questions:

  1. Why am I getting these FIREBASE WARNING: {} messages?
  2. What could be causing the timeouts on Vercel when it works locally?
  3. Are there specific optimizations or configurations I should consider for Firebase or Vercel to avoid these timeouts?

Any insights or suggestions on what might be going wrong would be greatly appreciated. Thank you!


Solution

  • I resolved the issue by saving the private key in the environment variables without the surrounding quotes.

    Initially, I was storing the private key like this:

    PRIVATE_KEY="---BEGIN PRIVATE KEY----
    ShfkkJHNJK
    Jeidj
    ---END PRIVATE KEY----"
    

    But the correct way to store it in Vercel is without the quotes:

    PRIVATE_KEY=---BEGIN PRIVATE KEY----
    ShfkkJHNJK
    Jeidj
    ---END PRIVATE KEY----
    

    By removing the quotes, the Firebase Admin SDK was able to correctly read and initialize using the private key.


    This answer should help others who might be facing a similar issue with environment variables and Firebase Admin SDK.