Error loading 'protobuf.js' while retrieving Firestore document

When trying to run a basic node file with Firebase and Firestore, the following code was used:

const firebase = require("firebase");
const http = require('http')

require("firebase/firestore");

firebase.initializeApp({
  apiKey: '...',
  authDomain: '...',
  databaseURL: '...',
  serviceAccount: '...',
  projectId: '...'
});

var db = firebase.firestore();
var userRef = db.collection('...').doc('...');

However, upon running this code, an unexpected error occurred in the terminal:

Firestore (4.5.2) 2017-10-18T19:16:47.719Z: INTERNAL UNHANDLED ERROR: Error: Failed to fetch file at /.../project/node_modules/protobufjs/dist/protobuf.js:5164:30 at ReadFileContext.callback (/.../p/node_modules/protobufjs/dist/protobuf.js:358:29) at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:420:13) (node:43981) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Failed to fetch file (node:43981) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

The necessary protobuf.js file was present in the node_modules folder and reinstalling it did not resolve the issue. It seems that the problem is specific to this setup and version of protobuf.js.

Answer №1

Similar Problem:

const firebase = require('firebase');
require("firebase/firestore");
const config = {
  apiKey: "-redacted-",
  authDomain: "-redacted-",
  databaseURL: "-redacted-",
  projectId: "-redacted-",
  storageBucket: "-redacted-",
  messagingSenderId: "-redacted-"
};
firebase.initializeApp(config);
let db = firebase.firestore();
let ref=db.collection('example').doc('test');
ref.set({test:true});

Error Output in console (Node v6.11.4):

Firestore (4.5.2) 2017-10-18T19:48:00.297Z: INTERNAL UNHANDLED ERROR:  Error: Failed to fetch file
at Error (native)
at /Users/krispy.uccello/Development/devrel/constellation/functions/node_modules/protobufjs/dist/protobuf.js:5164:30
at ReadFileContext.callback (/Users/krispy.uccello/Development/devrel/constellation/functions/node_modules/protobufjs/dist/protobuf.js:358:29)
at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:367:13)

(node:71564) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Failed to fetch file

Database Access Rules:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

Update: This problem appears to be related specifically to writing operations. Reading data from Firestore seems to be functioning correctly.

Update #2: A firebase function was implemented to handle the write operation successfully. The issue could potentially be linked to the version of protobuf js being used on the client side. Despite uncertainties regarding the Firebase end's version, it seems to be working fine. Below is a sample function invoked through a firebase https trigger - it executes as expected and data is stored in the firestore database.

function writeWorkerProfile(id, data, res) {
  let ref = 
  db.collection('scratch').doc('v1').collection('workers').doc(`${id}`);
  ref.set(data)
  .then(function() {
    console.log("Document successfully written!");
    res.status(200).send({ok:true})
  })
  .catch(function(error) {
      console.error("Error writing document: ", error);
      res.status(500).send('Error occurred: Could not write data');
  });
}

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

Adding elements to my state array - Utilizing Nextjs/React/Javascript

After fetching data from 2 different APIs that each return an object, I have stored them in separate states. Now, I want to merge these two objects into a single state that contains both of them as an array. However, when I try to do this, the second obj ...

Code activates the wrong function

Below is a snippet of HTML and JS code for handling alerts: HTML: <button onclick="alertFunction()">Display Choose Option Modal</button> <button onclick="alertFunction2()">Display Veloce Modal</button> JS: function alertFunct ...

Which is better for handling events - jQuery delegation or function method?

Which approach is quicker and has broader browser support? 1. Utilizing a JavaScript function such as: function updateText(newtext) { $('div#id').text(newtext); } and incorporating it into an element's onclick event: <button onc ...

Do two Express JS applications run on separate threads?

Running two express apps on different ports raises the question of whether they assign themselves to different cores, knowing that express typically runs on a single thread. The cluster module, however, replicates the express app and allows them to utiliz ...

Is there a way for me to access the response from the PHP file I'm calling with Ajax?

I am just starting to explore ajax and jquery, and I recently found a code online that I'm tweaking for my own use. However, I am struggling with how to handle responses from PHP in this context. The current setup involves ajax POSTing to a php page ...

What is the best way to implement Axios for data fetching in Gatsby's useStaticQuery function?

One way to fetch data in Gatsby is by using GraphQL, like in the following example: import { graphql, useStaticQuery } from "gatsby" const IndexPage = () => { const gatsbyRepoData = useStaticQuery(graphql` { github { repo ...

Retrieve a collection within AngularFire that includes a subquery

I have the following function getParticipations( meetingId: string ): Observable<Participation[]> { return this.meetingCollection .doc(meetingId) .collection<ParticipationDto>('participations') .snapshotCh ...

Why am I receiving the "Unsupported Error" message while attempting to execute chai mocha tests in GitLab Ci/Cd pipeline?

Attempting to execute a basic mocha test within a GitLab Ci/Cd pipeline. The application utilizes nodejs, express, and typescript. Here is the breakdown of the directory structure: - root - backend - src - index.ts - ...

Can we streamline this jQuery code by utilizing .hasClass and .bind?

Can this code be simplified? Initially, when #griffyindor has the 'active' class, I want all other houses (slytherin, ravenclaw, and hufflepuff) to show. If at any point it loses the 'active' class upon clicking something else, I want ...

How can I retrieve values of selected checkboxes using the Express Data API?

I have a scenario where I need to retrieve data from input checkboxes only when the checkbox for my express post function is selected. There are 3 checkboxes with values of 1000, 2000, and 3000 as follows: <input type="checkbox" name=" ...

Is there a more efficient method for a logged-in user to trigger a cloud function and retrieve data from Firestore in Firestore?

I manage a website that stores data in Cloud Firestore. In order to keep the database updated with fresh information, I regularly pull data from various APIs and store it. However, my current method of providing users with this real-time data involves thei ...

Issue with popup display in React Big Calendar

I'm currently working on a calendar project using React-Big-Calendar, but I've run into an issue with the popup feature not functioning properly. <div className={styles.calendarContainer} style={{ height: "700px" }}> <C ...

Identify the quantity of dynamically added <li> elements within the <ul> using jQuery

I'm facing an issue where I need to dynamically add a list of LI items to a UL using jQuery. However, when I try to alert the number of LI elements in this list, it only shows 0. I suspect that it's because the code is trying to count the origina ...

The changes to the grid options do not reflect immediately on the UI Grid interface

I am currently working on a project using the UI Grid module in AngularJS. I want to include row filtering as an option, but since not all users require it and the filter boxes take up a lot of space, I decided to disable filtering by default and add a but ...

What is the process for including an additional button in the DateTimePicker feature of material UI?

I'm currently utilizing DateTimePicker in my React application. https://i.sstatic.net/ShyTE.png I wish to incorporate a Clear button positioned to the left of the Cancel Button. import { MuiPickersUtilsProvider, DateTimePicker } from "@material-ui/ ...

Node encountering an ENOENT error while invoking the Ffmpeg binary through the Fluent-Ffmpeg API

Scenario I am currently developing a Firebase function in Node.js. The main goal is to trim an incoming audio clip to a specific length using FFmpeg and Fluent-FFmpeg. Challenge However, I encountered an issue when the function is triggered in Firebase. ...

Is it possible to handle both ajax form submissions and browser post submissions in express.js?

On my website, I have implemented a contact form using express.js (4.0). I am contemplating how to manage the scenario where a user disables JavaScript. If the last part of my routing function looks like this: res.render('contact.jade', { tit ...

Developing a trivia game using HTML and JavaScript

I'm in need of some serious assistance with creating a quiz using HTML. My goal is to have a web page where users can visit, take a quiz, and have their responses stored. Unfortunately, I don't have the knowledge or skills required to do this on ...

Comparing Encrypted Passwords with Bcrypt

Encountering an issue with comparing passwords despite accurately storing the hashed password during registration. Database - MongoDB Node.js version - v18.17.0 Bcrypt version - 5.1.1 Below is my userSchema: const userSchema = new mongoose.Schema({ u ...

The destination where data is transmitted via POST to a PHP file using the HTTPRequestObject.send method

Can anyone help me figure out where the HTTPRequestObject stores strings that I have sent using the "POST" method to a PHP file? I have checked both the $_POST and $_REQUEST arrays but cannot find them. This is how I am sending the data from JavaScript: ...