I'm encountering a persistent "TypeError: Cannot read properties of undefined (reading 'document')" error when deploying my Firebase Cloud Functions, even though my import statements and code appear to be correct. This error occurs when trying to define a Firestore trigger using functions.firestore.v2.document(...)
.
Code:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const axios = require("axios");
const { FieldValue } = require('firebase-admin/firestore');
admin.initializeApp();
const db = admin.firestore();
exports.rahh = functions.firestore.v2.document("user/{userId}").onCreate(async (event) => {
// ... (My function logic here - fetching data from Google People API) ...
});
Error Message:
TypeError: Cannot read properties of undefined (reading 'document')
at Object. (C:\path\to\my\functions\index.js:9:39)
... (Rest of the stack trace) ...
Problem:
Despite having the correct import (const functions = require("firebase-functions");
) and initializing the Firebase Admin SDK (admin.initializeApp();
), the firestore property on the functions object is undefined, causing the error.
What I've Tried:
Emulator Reset: firebase emulators:stop, firebase emulators:clear, firebase emulators:start --only functions
Node Version: Switched to Node 18 (using nvm).
Emulator Run: When running on the emulator it worked perfectly.
Package Lock File: Removed package-lock.json and node_modules, then npm install
Global Firebase CLI: npm install -g firebase-tools
Simplified index.js: Created a minimal index.js with a simple HTTPS function (and that worked!)
Checked main in package.json: The main field is correctly set to "index.js".
Double-checked for typos: Confirmed no typos in imports or function calls.
Used a basic text editor: Edited index.js in Notepad to rule out IDE issues.
package.json:
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": { /* ... */ },
"engines": { "node": "18" },
"main": "index.js",
"dependencies": {
"axios": "^1.7.9",
"firebase": "^11.2.0", // Firebase client SDK (might not be needed in functions)
"firebase-admin": "^13.0.2",
"firebase-functions": "^6.3.1"
},
"devDependencies": { /* ... */ },
"private": true
}
Firebase CLI Version: 13.29.3
The fact that a new project works points to a configuration issue, but I can't identify it.
What could be causing this "undefined" error, even with the correct imports and after trying all the troubleshooting steps above?
You're trying to use v2 Cloud Functions, but using the v1 syntax.
In the documentation on extending Firestore with Cloud Functions (2nd gen) it shows this:
import {
onDocumentWritten,
onDocumentCreated,
onDocumentUpdated,
onDocumentDeleted,
Change,
FirestoreEvent
} from "firebase-functions/v2/firestore";
exports.myfunction = onDocumentWritten("my-collection/{docId}", (event) => {
/* ... */
});
For v1/gen2 you'll want to model after that, with a top-level onDocumentCreated
import rather than the namespaced syntax.