The step-by-step guide to launching a server using Firebase Cloud Functions

After following a tutorial to set up an express server for accessing a MongoDB instance on Google Cloud Platform, I encountered an issue when deploying my Firebase functions. When I run the command

firebase deploy --only functions

All functions deploy successfully except for the mongoServer function, resulting in the error message:

functions: the following filters were specified but do not match any functions in the project: mongoServer

This situation is perplexing considering the steps outlined in the tutorial.

What could be causing this problem?

Here is a snippet from my functions/index.ts file:

import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions';
import { mongoApp } from './mongo/mongo-server';
import { onSendNotification } from './notifications/send-notification';
import { onImageSave } from './resize-image/onImageSave';
admin.initializeApp();

export const onFileChange = functions.storage.object().onFinalize(onImageSave);
export const sendNotification = functions.https.onRequest(onSendNotification);
export const mongoServer = functions.https.onRequest(mongoApp); // encountering deployment failure here

And here is the essential part of my mongo-server.ts file:

import * as bodyParser from 'body-parser';
import * as express from 'express';
import * as mongoose from 'mongoose';
import { apiFoods } from './foods.api';
import { Mongo_URI, SECRET_KEY } from './mongo-config';

const path = require('path');

export const mongoApp = express();

mongoApp.set('port', (process.env.PORT || 8090));
mongoApp.use(bodyParser.json());
mongoApp.use(bodyParser.urlencoded({ extended: false }));

connect()
  .then((connection: mongoose.Connection) => {
    connection.db
      .on('disconnected', connect)
      .once('open', () => {

        console.log('Connected to MongoDB');
        apiFoods(mongoApp);

        mongoApp.listen(mongoApp.get('port'), () => {
          console.log('Listening on port ' + mongoApp.get('port'));
        });

      });
  }).catch(console.log)

function connect(): Promise<mongoose.Connection> {
  return mongoose
    .connect(Mongo_URI)
    .then((goose) => { return goose.connection })
    .catch(err => {
      console.log(err)
      return null;
    });
}

Answer №1

When deploying an express app to Cloud Functions, it is important to note that the app cannot manage its own connections. Express can only be used to set up routes for Cloud Functions to send requests to. Cloud Functions handles all incoming connections on its own.

For a basic example involving express and Cloud Functions, check out this resource.

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

How to automatically scroll to the most recently added element in an *ngFor loop using Angular 2

In my web page, I have a dynamic list rendered using an ngFor loop. Users can add or remove elements from this list by clicking on a button. What I want to achieve is to automatically scroll the browser view to the latest element added when a user clicks o ...

JavaScript encountered an issue as it attempted to reference the variable "button" which was

I am currently working on developing a new API, but I have encountered some issues with JavaScript: Below is my JS/HTML code snippet: const express = require('express'); const app = express(); const PORT = 3000; submit.onclick = function() ...

Define two categories within the Attributes interface

To avoid theme-ui errors in the sx prop, I need to declare both of these statements: declare module "react" { interface Attributes { sx?: ThemeUIStyleObject; } } and declare module "react" { interface Attributes { sx?: Sx ...

Is there a way to generate an Excel file and send it to the client's browser using a file stream in the Node Express response?

I am eager to implement a feature in my Node Express project where I can generate an Excel File stream and send it directly to the client browser for download. However, my lack of experience with streams is making me unsure about the feasibility of this ta ...

Unable to utilize the "let" keyword in WebStorm

Currently, I am delving into learning typescript and attempting to create a simple 'let' statement. However, I encountered an error indicating the need to use ECMAScript 6 or later versions. The exact message from the typescript compiler states: ...

The function user.setPassword is not available at this time (While resetting password)

My express app uses passport for user authentication, which is working fine. However, I am facing an issue while trying to implement a password reset feature. The error message I receive is: TypeError: user.setPassword is not a function I have researched ...

Disable TS4023 error in TypeScript: Unable to name external module "xyz"

//custom-slice.js import { createCustomSlice } from '@my/data-toolkit'; /* ***********************For Managing all the divisions data****************************** */ export const divisionDataSlice = createCustomSlice({ name: 'divisionda ...

Learn the process of uploading files with the combination of Angular 2+, Express, and Node.js

Need help with uploading an image using Angular 4, Node, and Express with the Multer library. Check out my route.js file below: const storage = multer.diskStorage({ destination: function(req, file, cb) { cb(null, 'uploads') }, filename: fun ...

Exploring Angular Firebase: Effectively iterating through a list object to extract important data

I am attempting to retrieve location data from a database, iterate through it, and display markers on a map. Currently, I am pulling the data using the following code: this.msgData = this.db.list(`/messages/`).valueChanges(); this.msgData.take(1).subscrib ...

What is the best way to invoke a function with multiple parameters in TypeScript?

I have a function that manipulates a specified query string, along with another version that always uses window.location.search. Here is the code snippet: class MyClass { public changeQuery(query: string; exclude: boolean = true; ...values: string[]): st ...

What is the process for incorporating a new view or route in Express?

I am a beginner in this field and eager to learn as much as I can. Currently, I am utilizing the template available at https://github.com/primaryobjects/Node.js-Bootstrap-Starter-Template. Things were going smoothly until I attempted to add a new page, whi ...

Ways to obtain the Map object from HTTPClient in Angular

When calling a REST endpoint, the return type is as follows: ResponseEntity<Map<String, List<Object>>> How can I handle this response on the Angular side? I attempted the following approach: let requiredData = new Map<String, Array&l ...

Looking for a way to configure webpack with typescript and style loaders for your project template

I recently set up a Vue project using Webpack and typescript, but I ran into some errors when trying to add a <template> element in my .vue file along with a <style> element that caused issues with my webpack watcher displaying errors. Below i ...

Unable to change the Content-Disposition to 'inline' in Firebase Storage using the Admin SDK for Node.js

Is there a way to change the default content-disposition: attachment HTTP header in Firebase Storage to content-disposition: inline for displaying public images directly in the browser (via <a href="..."> links) instead of forcing them to download? ...

Utilizing Node.js on Linux to Connect to SQLServer

Looking to create a REST service using Node.js and Express but facing difficulties connecting to a SQLServer 2000 database. The Microsoft connector is not compatible with Linux, as mentioned by the developers: The Microsoft Driver for Node.JS for SQL Se ...

Is there a way to communicate with the Microsoft bot from within the bot itself, ensuring that the message follows the dialog flow and receives the appropriate response?

It would make more sense if the title of this were "how can I ensure the bot responds smoothly in case context is lost or there's a server restart during a user interaction with the bot. It's confusing as it is and I need to break down the planni ...

DuplicateModelError: Unable to duplicate model after it has been compiled, React.js, MongoDB, TypeScript

In the early stages of developing an application using Next.js, Mongoose, and Typescript, I encountered a persistent issue. Whenever I attempt to send a request through Postman after clicking save, it fails, displaying the error message: OverwriteModelErr ...

What is the best way to retrieve a variable from a ReaderTaskEither within an error handling function using fp-ts?

I'm facing a challenge with my code that involves the usage of ReaderTaskEither: export const AddUserToTeam = ({ userId, teamId }: AddUserToTeamDto) => { return pipe( // ...

Angular: Understanding Render Delay Caused by *ngIf and Expression Changes from Filters

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: false'. Current value: 'ngIf: true'. Encountering the above error in the console. In my code, I have filters that control ...

Node/Express API returning empty body when being accessed through fetch or axios requests

Currently working on integrating an API call in a React app using Node/Express. No matter where I place the fetch/axios call, the parsed body always shows up as undefined in my controller. Yesterday, I was experimenting with fetch but decided to switch to ...