firebase / firebase/firebase-admin-node

[FR]

Abierto
#2,910 1 comentario 0 reacciones 0 asignados Ver en GitHub
needs-triage type: feature request
Lenguaje dominante
TypeScript
Estrellas
1.7k
Forks
419
Merge medio
3 d 10 h
PR fusionados (30 d)
16

Descripción

Summary: TypeError: db.writeBatch is not a function in Next.js API Route using firebase-admin

1. Problem Description:

We are encountering a persistent TypeError: db.writeBatch is not a function error when attempting to use Firestore batch writes via the firebase-admin SDK within a Next.js API Route. Logs indicate that the Admin SDK initialization and the retrieval of the Firestore instance (db) appear successful, but the db.writeBatch() method is unavailable at the point of execution.

2. Development Environment:

OS: Windows
Project Location: C:\Users\kotec\web-excel-saas (Note: User mentioned potential write restrictions on C: drive, but core build/install processes seemed functional, making this unlikely the direct cause of the TypeError).
Node.js Versions Tested: v22.15.0, v20.19.1, v18.20.8 (Error persisted across all versions).
Next.js Versions Tested: v15.3.1 (w/ React 19), v14.2.x (w/ React 18) (Error persisted across both versions).
firebase-admin Versions Tested: v13.3.0, v12.7.0 (Error persisted across both versions).
firebase (Client SDK) Version: v11.6.1
3. Code Structure & Error Location:

The error originates within a shared module (lib/data/firestore.js) specifically in the saveExcelCellsToFirestore function, which is called by a Next.js API Route handler (/api/excel/upload).
The lib/data/firestore.js module handles Firebase Admin SDK initialization upon server startup.
Service account credentials were loaded from environment variables (.env.local). Both methods were tested: using a file path (FIREBASE_SERVICE_ACCOUNT_KEY) and using individual components (FIREBASE_PROJECT_ID, FIREBASE_CLIENT_EMAIL, FIREBASE_PRIVATE_KEY).
The SDK is initialized as a named app using admin.initializeApp(..., 'webExcelAdmin'), including checks to prevent duplicate initialization.
The Firestore instance (db) is successfully obtained using const app = admin.app('webExcelAdmin'); db = app.firestore();. Success logs related to this step were confirmed.
Debugging confirmed that within the saveExcelCellsToFirestore function, the db object appears to be a valid Firestore instance.
typeof db.collection correctly returns 'function'.
Calling db.collection('test') executes successfully.
However, typeof db.writeBatch consistently returns 'undefined', leading to the TypeError when const batch = db.writeBatch(); is executed.
4. Troubleshooting Steps Performed:

Version Changes: Tested multiple compatible combinations of Node.js (v18, v20, v22), firebase-admin (v12, v13), Next.js (v14, v15), and React (v18, v19). The error persisted.
Clean Installs: Deleted node_modules, lock files (package-lock.json), and .next build cache multiple times before running npm install for each version change.
Initialization Methods: Tested initializing the Admin SDK using both the service account file path and individual key components via environment variables. Confirmed Firestore instance retrieval using app.firestore().
Standalone Test: Created a minimal Node.js script (test-firebase.js) outside the Next.js environment. This script also failed to find db.writeBatch (returned undefined) when tested with Node v22 + firebase-admin v12.
Environmental Factors: Ruled out firewalls, Firebase plan limits, and C: drive write permissions as likely direct causes for this specific TypeError.
5. Final Conclusion:

Despite exhaustive troubleshooting across multiple verified configurations and environments, the Firestore instance object (db) obtained via admin.app(...).firestore() consistently lacks the writeBatch method. Other core methods like collection are present and functional. The root cause remains unidentified but strongly suggests a very specific, environment-related bug or incompatibility involving the interaction between Node.js (v18+), firebase-admin (v12/v13), and potentially the runtime/build environment (possibly exacerbated by Next.js, although the standalone test also failed), specifically affecting the availability of the writeBatch method.

Hopefully, this summary provides enough detail for the developers to understand the situation. Good luck

Guía de contribución

Abrir la guía de contribución

Línea de trabajo

Comienza con lib/data/firestore.js y el handler /api/excel/upload; después, compara su inicialización de Firestore con el script independiente test-firebase.js. Reproduce el método db.writeBatch faltante en las versiones de Node.js y firebase-admin indicadas, comprobando la instancia devuelta por app.firestore(). Se considera terminado cuando se haya identificado la causa y documentado una resolución verificada.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
next.js, node.js, typescript
Área
api, backend, database
Tipo de issue
Error
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Estancado
Claridad
Necesita aclaración
Aptitud para principiantes
25/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.