Vercel Deployment Experiencing Timing Out Issues with Firebase Realtime Database Requests, Local Environment Works Fine

I'm facing an issue while trying to make requests to my Firebase Realtime Database from a Vercel-deployed application. The requests are successful in my local development environment, both in development and production modes. However, once deployed on Vercel, I consistently encounter timeouts and Firebase warnings.

Sample Code That's Failing:

Below is 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,
  });
}

// Other code omitted for brevity

Notable Points:

  • Firebase Realtime Database is throwing warnings, but the message is empty.
  • Vercel is returning multiple 504 Gateway Timeout errors, 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: {}

// More log entries...

Steps Taken So Far:

  • Confirmed stable internet connection.
  • Checked database size and latency, which shouldn't be causing issues.
  • Using Firebase Admin SDK to interact with Firebase services.

Firebase Initialization Code:

Here’s a condensed version of the Firebase initialization code used in the 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,
  });
}

// Other Firebase initialization exports...

Situation Overview:

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

Queries:

  1. Why am I receiving these `FIREBASE WARNING: {}` messages?
  2. What could be triggering the timeouts on Vercel whereas it operates smoothly locally?
  3. Any specific optimizations or setups recommended for Firebase or Vercel to avoid such timeouts?

Your insights or suggestions on what might be going wrong would be highly valued. Thank you!

Answer №1

I managed to solve the problem by storing the private key in the environment variables without any quotation marks.

Initially, I had stored the private key like this:

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

However, the correct method for Vercel is to store it without the quotes:

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

By eliminating the quotes, the Firebase Admin SDK was able to properly interpret and initialize using the private key.


This explanation will hopefully assist others who are encountering a similar issue with environment variables and the Firebase Admin SDK.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for resolving error TS6143: '`--allowJs` option is not enabled'

An error with code TS6143 occurred when trying to run npm start. The error message is as follows: src/main.ts Module './radio-ng-model-example' was resolved to 'C:/Users/saish/Documents/my-app/quickstart/src/radio-ng-model-example.js', ...

Error: The argument provided for user.token is of type 'string | undefined' which cannot be assigned to a parameter of type 'string'

I'm currently engaged in a project that involves ASP.NET Core Web API and Angular 13. Here is the login post request from the endpoint: > https://localhost:44396/api/v1/auth/login { "status_code": 200, "message&qu ...

The Authorization Header sent by Angular is always null

I've been attempting to send a request with an authorization header using Angular to communicate with a Spring backend. export class TokenInterceptor implements HttpInterceptor{ constructor(public sharedService : SharedService){} intercept(r ...

Bringing @angular/code into a directory that is not within an Angular project

Currently, I have an Angular 2 project folder with a separate service folder named "auth.service.ts" located outside of it. Within this service file, I am importing `Injectable` from `@angular/core`. However, due to the service being located outside of t ...

Is my Javascript experiencing a shortage of asyncIds? (Encountered RangeError in inspector_async_hook.js)

One issue that I frequently encounter while using async/await is the following error: RangeError: Value undefined out of range for undefined options property undefined at Set.add (<anonymous>) at AsyncHook.init (internal/inspector_async_hook ...

Guide to releasing a NestJs library on npm using the nrwl/nx framework

Struggling with creating a publishable NestJS library using NX. Despite reading numerous documentations, I still can't figure it out. I've developed a NestJS library within an NX monorepository and now I want to publish just this library on NPM, ...

"Utilizing TypeScript to assign specific types to recognized keys while also accommodating for undefined

Is there a way to declare an object in such a manner that it requires certain keys, while also allowing for the inclusion of any other keys? Let's say we have an object called student which must always include the keys name and gender, but can also h ...

Issue encountered during rendering: "TypeError: Attempting to access property '_t' of an undefined object" while running a Unit Test using Jest

I spent hours troubleshooting a unit test for my Vue.js component, but no matter how much I searched the internet, I kept encountering this error: console.error node_modules/vue/dist/vue.runtime.common.dev.js:1884 TypeError: Cannot read property ' ...

The template displays an <object Object>, yet the observable async pipe functions without any errors

I am working with an observable of todos that have properties such as id, title, and completeness. TodosComponent/index.ts import {Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core'; import {Todo, ITodo} from &a ...

Using injected services within static methods may seem tricky at first, but once you

I am exploring the integration of angularjs and typescript in my project. Currently, I am working on creating an Orm factory using typescript but have encountered some challenges. The structure of my factory class is as follows: class OrmModel implements ...

`The error "mockResolvedValue is not recognized as a function when using partial mocks in Jest with Typescript

Currently, I am attempting to partially mock a module and customize the return value for the mocked method in specific tests. An error is being thrown by Jest: The error message states: "mockedEDSM.getSystemValue.mockResolvedValue is not a function TypeEr ...

Is there a way to modify the format received from the backend Angular REST API?

Below is the code I am currently using: this.elService.getOne(id) .subscribe((result: ModelName) => { let test = this.datePipe.transform(result['birthDate'], 'mm/dd/yyyy') result['birthDate']= test console.log(result ...

Error: The terminal reports that the property 'then' cannot be found on the data type 'false' while trying to compile an Angular application

In my Angular application, which I initiate through the terminal with the command ng serve, I am encountering build errors that are showing in red on the terminal screen. ✔ Compiled successfully. ⠋ Generating browser application bundles... Error: s ...

Complicated connections between TypeORM and MySQL

Currently leveraging TypeORM in tandem with MySQL, my database comprises of two main Entities, namely User and Project: @Entity() class User { @PrimaryGeneratedColumn('uuid') id: string; @Column({}) name: string; } @Entity() ...

What to do when the 'image' property in Next.js next/image has an implicit 'any' type and needs fixing?

I'm a newcomer to Next.js and TypeScript and I can't seem to find any helpful resources on resolving this particular issue: import Image from 'next/image'; export default function Item({ image }) { // <-- parameter image needs a &ap ...

What is the best way to repair a react filter?

Recently, I successfully created a database in Firebase and managed to fetch it in React. However, my current challenge is to integrate a search bar for filtering elements. The issue arises when I search for an element - everything functions as expected. ...

How to utilize FileReader for parsing a JSON document?

I'm currently facing an issue while attempting to read and copy a JSON file uploaded by the user into an array. When using .readAsText(), the returned data includes string formatting elements like \" and \n. Is there a way to utilize FileRe ...

Sorry, it seems like there is an issue with the Typescript error that states: "The expression you are trying to call is not valid. The type 'typeof import("koa-session")

Partially resolved: An issue has been identified on Github regarding this problem. It seems that declaring a module in a global scope rewrites the types of the entire exported module, while declaring a module within another module merges the types. This b ...

Using the currency pipe with a dynamic variable in Angular 2

My application utilizes CurrencyPipe, The current implementation is functional, <div class="price">{{123 | currConvert | currency:'USD':true:'3.2-2'}}</div> Now, I need to dynamically pass the currency from a model varia ...

Variable type linked to interface content type

Is it possible to link two fields of an interface together? I have the following interface: export interface IContractKpi { type: 'shipmentVolumes' | 'transitTime' | 'invoices'; visible: boolean; content: IKpiContent; } ...