What could be causing the issue with deploying this straightforward Firebase function process?

Looking to implement a straightforward cloud function for adding a newly created user to Firestore:

./firebaseConfig.ts :

const app = initializeApp({
  ...
});

export const fireStoreDB = getFirestore(app);

./functions/index.ts :

import * as functions from 'firebase-functions';
import {DocumentData, DocumentReference, doc, setDoc} from 'firebase/firestore';
import {fireStoreDB} from '../../firebaseConfig';

const createDocumentReferenceHelper = <T = DocumentData>(
    collectionStartingPath: string,
    collectionPath: string[],
) => {
    return doc(
        fireStoreDB,
        collectionStartingPath,
        ...collectionPath,
    ) as DocumentReference<T>;
};

export const newUser = functions.auth.user().onCreate(async (user) => {
    const docRef = createDocumentReferenceHelper('users', [user.uid]);
    await setDoc(docRef, {email: user.email});
});

During deployment, I encountered the following error:

✔  functions: Finished running predeploy script.
i  functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i  functions: ensuring required API cloudbuild.googleapis.com is enabled...
i  artifactregistry: ensuring required API artifactregistry.googleapis.com is enabled...
✔  artifactregistry: required API artifactregistry.googleapis.com is enabled
✔  functions: required API cloudfunctions.googleapis.com is enabled
✔  functions: required API cloudbuild.googleapis.com is enabled
i  functions: preparing codebase default for deployment
i  functions: preparing functions directory for uploading...
i  functions: packaged /Users/<user>/<project>/functions (105.98 KB) for uploading
✔  functions: functions folder uploaded successfully
i  functions: updating Node.js 16 function newUser(us-central1)...

Function failed on loading user code. This is likely due to a bug in the user code. Error message: Error: please examine your function logs to see the error cause: 

https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging. Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation.

Functions deploy had errors with the following functions:
    newUser(us-central1)
i  functions: cleaning up build files...

Error: There was an error deploying functions

Troubleshooting steps taken:

  • Testing the 'newUser functionality' outside of the Cloud function, where it operates correctly.

  • Substituting newUser function with an HTTP hello world function, which deploys and functions without issues.

  • Reviewing the error logs, but only finding repetitions of the message indicating erroneous code.

Expectations:

Hoping for a simpler process ;). Assuming there's a basic oversight causing the problem.

Any guidance or assistance would be greatly appreciated!

Answer №1

After some thorough investigation, I realized that I had been overcomplicating things unnecessarily. The error logs in the Google Cloud console led me to discover that I had mistakenly used code from a different section of my project:

  • Project folder
    • functions(firebase / Google cloud)
    • src
    • firebaseConfig.ts

Within the firebaseConfig.ts file, I set up Firebase and Firestore and exported it for use in the src folder:

const app = initializeApp({
  ...
});

export const fireStoreDB = getFirestore(app);

However, firebase functions run in a trusted environment and therefore require the admin sdk to be enabled and initialized in the index file within the functions folder:

import * as functions from 'firebase-functions';
import * as firebaseAdmin from 'firebase-admin';

firebaseAdmin.initializeApp();
const db = firebaseAdmin.firestore();

export const newUser = functions.auth.user().onCreate((user) => {
    db.doc(`users/${user.uid}`).set({email: user.email});
});

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

Error message is not shown by React Material UI OutlinedInput

Using React and material UI to show an outlined input. I can successfully display an error by setting the error prop to true, but I encountered a problem when trying to include a message using the helperText prop: <OutlinedInput margin="dense&quo ...

What's the best way for me to figure out whether type T is implementing an interface?

Is it possible to set a default value for the identifier property in TypeScript based on whether the type extends from Entity or not? Here's an example of what I'm trying to achieve: export interface Entity { id: number; // ... } @Compon ...

Utilize [markdown links](https://www.markdownguide.org/basic-syntax/#

I have a lengthy text saved in a string and I am looking to swap out certain words in the text with a highlighted version or a markdown link that directs to a glossary page explaining those specific words. The words needing replacement are contained within ...

Data is not displaying correctly in the Angular Material Table

I'm currently trying to build a mat table based on an online tutorial, but I'm facing a problem where the table appears empty even though I have hard coded data. As someone new to Angular and HTML/CSS, I'm struggling to understand why the ma ...

When you compile TypeScript with the target set to 'ES3' or 'ES5', it creates an internal structure

Recently delved into the world of TypeScript and experimenting with webpack ts-loader and babel-loader to compile and transpile TypeScript into ES5. However, I came across a compiler option in tsc that can target 'ES5', which made me question the ...

ViewChild with the focus method

This particular component I'm working on has a hidden textarea by default : <div class="action ui-g-2" (click)="toggleEditable()">edit</div> <textarea [hidden]="!whyModel.inEdition" #myname id="textBox_{{whyModel.id}}" pInputTextarea f ...

Vite is turning a blind eye to compiler errors until the specific file is executed during runtime

There's an odd issue with Vite that allows me to log in to my app and use it freely, until I click on a page that triggers a compilation error. Once that happens, the page won't render and the error is displayed in the console. Strangely enough, ...

Issue with the display of JQuery slider within TypeScript Angular directive in C# environment

I am encountering an issue with implementing a JQuery slider in my application. When I use it solely with JQuery, it functions properly. However, when I incorporate it into an angular directive built with typescript, the display is not as expected. https: ...

Unit testing with Jest in TypeScript for mocking Express and Mongoose

I've been struggling to find comprehensive resources on using jest.fn() to mock TypeScript classes and their methods, like express' Request, Response, NextFunction, and the save() method on a mongoose model. For instance, suppose I have the foll ...

Attaching the JSON data to ngModel in Angular 2

I have received a json response containing various fields, including the rewards.rewardName value. I'm trying to figure out how to bind this specific value to [(ngModel)] in Angular 2. [ { "id": 18, "gname": "learning ramayanam", "goalCat ...

Exploring the differences between leveraging RxJS fromEvent and @ViewChild versus using the keyup event and RxJS Subject to detect changes in input

I have a simple component that allows users to search using the values typed into a search box. I've come across two different ways to implement this functionality and both seem to work well. Method 1 utilizes fromEvent from RxJS to create an observa ...

Transforming a singular function into a versatile, reusable function with the help of Typescript

In my component, I have a function dedicated to removing duplicate values from an array. const removeDuplicateScenarios = (scenariosList: Scenario[]): Scenario[] => { return _.filter(scenariosList, el => _.filter(scenariosList, e => e.id === el ...

What is the process for invoking instance methods dynamically in TypeScript?

There is an object in my possession and the goal is to dynamically invoke a method on it. It would be ideal to have typechecking, although that may prove to be unattainable. Unfortunately, the current situation is that I cannot even get it to compile: ...

`Angular2 Reactively-shaped Form Elements with BehaviorSubject`

As a newcomer to Angular, I am struggling with updating reactive forms after making asynchronous calls. My specific challenge involves having a reactive form linked to an object model. Whenever there is a change in the form, it triggers an HTTP request th ...

Enter the quiz that starts counting down as soon as you open it

Is there a way to develop a web application that can send emails to specific users with a link that expires in 3 days? When the user clicks on the link before it expires, a new browser window/tab will open with personalized questions and a countdown timer ...

A guide on showing an image from a JSON file path

As a beginner in Angular, I am currently working with Angular 8. I have a list of image paths stored in the 'dataSource' variable in JSON format, like so: hotdeals: Array(4) 0: {uri: "/Home/HotDeals/hotdeal1.png", id: "2"} 1: {uri: "/Ho ...

Using Cypress and JWT, automate the login process for JHipster

Is there a way to automate the bypassing of the JHipster login screen? This is my goal: let jwt_token before(function fetchUser() { cy.request('POST', '/api/authenticate', { username: 'user', password: &a ...

Having trouble integrating CKEditor into a React Typescript project

Error: 'CKEditor' is declared but its value is never read.ts(6133) A declaration file for module '@ckeditor/ckeditor5-react' could not be found. The path '/ProjectNameUnknown/node_modules/@ckeditor/ckeditor5-react/dist/ckeditor.js& ...

Performing actions simultaneously with Angular 2 directives

My custom directive is designed to prevent a double click on the submit button: import { Directive, Component, OnInit, AfterViewInit, OnChanges, SimpleChanges, HostListener, ElementRef, Input, HostBinding } from '@angular/core'; @Directive({ ...

Angular - Utilizing NgRx selector for efficient data update notifications

Is there a method to create a "data updated" indicator when I am not interested in the actual updated data itself? Consider a scenario with a reducer: const initialState: SomeReducer = { dataInQuestion: Array<SomeDto>, ... } Following an action ...