Firebase Cloud Function Local Emulator Fails to Retrieve Data with Error 404

My goal is to locally trigger a Firebase Cloud Function using the emulator. However, every time I try, the function returns a 404 Not Found status code and a response body of Cannot Get. The function is deployed locally and visible on the UI, but it fails with the above-mentioned errors when accessed.

The function deploys to this endpoint:

http://localhost:5001/project/region/health
and the command I use is:
firebase emulators:start --only functions

// app.ts
import * as express from 'express';
import * as functions from 'firebase-functions';
import { router as healthRouter } from './api/utils/router';

const healthApp = express();

healthApp.use('/health', healthRouter);

export = {
  health: functions.region('northamerica-northeast1').https.onRequest(healthApp),
};
// router.ts
import { Router } from 'express';
import { health } from './health';

export const router = Router();

router.get('/', health);
// health.ts
import type { Request, Response } from 'firebase-functions';
import * as functions from 'firebase-functions';

export const health = functions.https.onRequest(
  (req: Request, res: Response) => {
    res.status(200);
  }
);
// tsconfig.json
{
  "compilerOptions": {
    "module": "commonjs",
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "outDir": "lib",
    "sourceMap": true,
    "strict": true,
    "target": "es2017",
    "allowSyntheticDefaultImports": true
  },
  "compileOnSave": true,
  "include": [
    "src"
  ]
}

Answer №1

After exporting an express app through Firebase Function, the paths are adjusted to be relative to the exported function name. In this case, the app was exported as exports.health which means the root path of the function is set to /health. To access it, you would need to visit

http://localhost:5001/project/northamerica-northeast1/health
.

However, because a route handler for /health was defined using

router.get("/health", healthRouter)
, calling the function resulted in adding an extra "/health" to the URL, leading to http://localhost:5001/project/northamerica-northeast1/health/health.

The error message "Cannot GET /" occurs because the relative URL is set as "/" when calling the function at http://localhost:5001/project/northamerica-northeast1/health, and there is no handler configured for it (using router.get("/", healthRouter)).

To rectify the issue, modify your code as follows:

router.ts:

router.get('/', health);

app.ts:

healthApp.use('/', healthRouter);

health.ts:

export const health = functions.https.onRequest(
  (req: Request, res: Response) => {
    res.send('Hello World!')
    res.status(200)
  }
);

This will ensure a return with status: 200 and a response stating Hello World!. Additionally, remember to execute npm run build before running

firebase emulators:start --only functions

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

Acessing files from Azure Blob within the Aurelia UI: Download or View now!

I currently have my files stored in Azure and I am looking for a way to either download or view them on the client side. This is how I envision the process: Azure -> Api -> Client UI (Aurelia) While I have come across several C# examples, I am unsu ...

Next.js routes handlers do not have defined methods parameters

Struggling to find the cause of undefined params Currently delving into the world of Nextjs api routes, I keep encountering an issue where my params are coming up as undefined when trying to use them in the HTTP method. My setup includes prisma as my ORM ...

In order to effectively manage the output of these loaders, it may be necessary to incorporate an extra loader. This can be achieved by using the

I'm currently working with react typescript and trying to implement a time zone picker using a select component. I attempted to utilize the npm package react-timezone-select, but encountered some console errors: index.js:1 ./node_modules/react-timezo ...

What is the best way to transform a PredictResponse into a JSON format?

I'm currently working on accessing a VertexAI project using both a React frontend and a Python backend. I recently asked for help with sending requests to VertexAI from Node, as detailed here. While in the Python approach I can successfully make and ...

The validation for decimal numbers fails to function when considering the length

I've been struggling to come up with a regular expression for validating decimal numbers of a specific length. So far, I've tried using pattern="[0-9]){1,2}(\.){1}([0-9]){2}", but this only works for numbers like 12.12. What I'm aimin ...

Jest tests reveal potential errors indicating an object may be null

When running my Jest (typescript) test cases on mongoose Models, I encounter numerous errors such as: Error TS2531: Object is possibly 'null'. For example, consider the following code snippet where the error is reported on line 3: const user = ...

Having difficulty specifying the class type in Typescript

I am currently working on defining a 'Definition' type in Typescript. In this case, a Definition could be either a class constructor or an object. Here is the code snippet that illustrates my approach: if (this._isConstructor(definition)) { r ...

Issue with const declaration in Typescript and Node.js - initializer is missing

Encountering a syntax error with the following line of code. Error message: SyntaxError: Missing initializer in const declaration const dataMap : Map<string, any> = new Map(); ...

Showing Information without NgFor Directives

I have successfully displayed data without using a ngFor loop. However, it is currently showing all the quote information from multiple customers. The CSS is arranged in such a way that the discount div is positioned next to the customerinfo div. Below is ...

Error in Firebase cloud functions: The reference to the child is invalid. Please check the path provided as the first argument

I'm currently working on implementing push notifications by following this tutorial: https://www.youtube.com/watch?v=z27IroVNFLI Although the tutorial is a bit dated, there aren't many viable alternatives for Firebase web apps. When my cloud fu ...

Step-by-step guide: Mocking a fetch request in Jest using React with TypeScript

In my project, I am developing a react+ts application which allows users to search for other users using the GitHub API. The search input element in my app has the following structure : <input type="text" placeholder="Search us ...

Tips for creating a TypeScript function that is based on another function, but with certain template parameters fixed

How can I easily modify a function's template parameter in TypeScript? const selectFromObj = <T, S>(obj: T, selector: (obj: T) => S): S => selector(obj) // some function from external library type SpecificType = {a: string, b: number} co ...

The isMobile variable from useSettings is failing to update correctly when the window is resized in a Next

I’ve encountered an issue with determining the device type (mobile, tablet, or desktop) in my Next.js application. I’ve utilized the is-mobile npm package to identify the device type and passing this data through settings. However, the isMobile flag fa ...

Updating a list item in AngularFire2 triggers a change in the overall list

I have successfully implemented an update call to Firebase, but I am experiencing an issue where the list on which I am looping is being refreshed, causing my input field to lose focus. Is there a way for me to trigger the update without refreshing the or ...

Here's how you can transfer the AceEditor value to the component state in ReactJS by utilizing the onClick event of a button

I'm facing a challenge implementing a customized CodeMirror using ACE Editor. I've experimented with incorporating state alongside the 'onClick' button parameter, but I haven't been successful in making it functional. import Rea ...

Is there a way to verify in Angular whether an image link has a width and height exceeding 1000?

I'm currently working on a function that checks if an image linked in an input field has a width and height greater than 1000 pixels, and is in JPG format. Here's my approach: HTML: <input (change)="checkValidImage(1, product.main_photo)" [ ...

Show website traffic using TypeScript visitor counter

I need help adding a visitor counter to my website. I initially tried using the API from , but it seems that the server is currently down and I can no longer use it. I found another API at . How can I retrieve count data from this specific API endpoint ...

What is the method for retrieving data from a node in Firebase Realtime Database using TypeScript cloud functions, without relying on the onCreate trigger?

Being a beginner with Firebase and TypeScript, I have been struggling to retrieve values from a reference other than the triggered value. Despite finding answers in JavaScript, I am working on writing functions using TypeScript for real-time database for A ...

"Enhance your Vue 3 project with TypeScript and take advantage of smart template suggestions

Is it feasible to enable autocompletion/suggestions in the template section of a Single File Component (SFC) when using VS Code with Vue 3 and Typescript, particularly for component props? For instance, consider a basic component named UserComponent: < ...

Receiving an error when triggering an onclick event for a checkbox in TypeScript

I am creating checkboxes within a table using TypeScript with the following code: generateTable(): void { var table = document.getElementById("table1") as HTMLTableElement; if (table.childElementCount == 2) { for (var x = 0; x < 2; x++) ...