'NextJS getServerSideProps bypassing Firestore emulator

I have nextJS app with Firestore emulator running locally. In order to connect the emulator locally only, I have the following:

if (typeof window !== "undefined") {
    if (window.location.hostname === "localhost") {
        // Firestore
        const db = getFirestore();
        connectFirestoreEmulator(db, 'localhost', 8080);
    }
}

This works for most of the cases but not for getServerSideProps:

export const getServerSideProps: GetServerSideProps = async (context) => {
    const id: any = context.params?.id;
    if (id) {
        const task = await getDocument('tasks', id)
        return { props: { task } };
    }
    return { props: {} };
};

This call of getDocument will result in a request to Firestore and not the emulator. For the sake of clarity this is how getDocument looks like:

const getDocument = (collectionName: string, id: string) => {
    return new Promise((resolve, reject) => {
        const docRef = doc(firestore, collectionName, id);
        getDoc(docRef)
            .then(docSnapshot => {
                if (docSnapshot.exists()) {
                    resolve(docSnapshot.data());
                } else {
                    // doc.data() will be undefined in this case
                    console.log("No such document!");
                }
            })
            .catch(e => reject(e))
    })
}

All this led me to think that my connect function has never get called - connectFirestoreEmulator(db, 'localhost', 8080); That wouldn't be surprising given where getServerSideProps has been called. I started debugging and tried the following:

if (process.env.NODE_ENV === 'development') {
    // Firestore
    const db = getFirestore();
    connectFirestoreEmulator(db, 'localhost', 8080);
}

But interestingly this small change returns the following reference error: Cannot access 'firestore' before initialization, here - const docRef = doc(firestore, collectionName, id); Does anyone know why this is and do we have any workaround for it? A bit odd, In the first scenario the emulator is bypassed and in the second it just freaks out.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source