Search code examples
firebasegoogle-cloud-firestore

Expected type 'Firestore$1', but it was: a custom Firestore object


It's my first project in firebase, I'm trying to insert a document (through the emulator), from a Node.js app and I get the error:

Expected type 'Firestore$1', but it was: a custom Firestore object

This is how I initialize firebase:

import admin from 'firebase-admin'
import { connectFirestoreEmulator } from "firebase/firestore";

const firebaseConfig = {
    apiKey: "XXXXX",
    authDomain: "linkedincv-bdbec.firebaseapp.com",
    projectId: "linkedincv-bdbec",
    storageBucket: "linkedincv-bdbec.appspot.com",
    messagingSenderId: "472466845815",
    appId: "XXXXX",
    measurementId: "XXXXX",
};

// Initialize Firebase
const app = admin.initializeApp(firebaseConfig);

const db = admin.firestore();
connectFirestoreEmulator(db, 'localhost', 4000);

export {db}

My execution code is as follows:

import {db} from '../../../lib/middleware/firebaseInit'

export async function POST({request}) {
    try {
        const payload = await request.json();
        const uniqueUrl = payload.uniqueUrl;

        // const docRef = await setDoc(doc(db, "json_cv", "zied"), payload)
        const docRef = await db.collection("json_cv").doc("zied").set( payload)
        // Return the document ID of the stored object
        return {
            body: JSON.stringify({ documentId: docRef.id }),
            headers: { 'Content-Type': 'application/json' },
            status: 200
        };
    } catch (error) {
        // Handle any errors that occur during processing
        console.error(error);
        return {
            body: JSON.stringify({ error: 'Failed to store unique URL' }),
            headers: { 'Content-Type': 'application/json' },
            status: 500
        };
    }
}

I tried to import connectFirestoreEmulator from other sources but none worked for me. Example:

// import { connectFirestoreEmulator } from 'firebase-admin/firestore';

throws another error


Solution

  • Ok so I found an answer here

    if you are running a NodeJS backend/script, you must set the environement variable FIRESTORE_EMULATOR_HOST

    const useEmulator = true;
    
    if (useEmulator){
        process.env['FIRESTORE_EMULATOR_HOST'] = 'localhost:8080';
    }
    
    admin.initializeApp({ ... });
    

    Thus there's no need to use the function

    import { connectFirestoreEmulator } from "firebase/firestore";