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

Getting Started with NextJs and Firestore Setup

Recently, I have been incorporating Firebase into my NextJs project. I've set up a file called initFirebase.tsx for the server-side implementation. import * as Sentry from '@sentry/nextjs'; import * as admin from 'firebase-admin'; ...

Wait until a svelte store value is set to true before fetching data (TypeScript)

I have implemented a pop-up prompt that requests the user's year group. Since I have databases for each year group, I need to trigger a function once the value of userInfo changes to true. My JavaScript skills are limited, and my experience has been ...

Dealing with the endless looping problem in Next.js caused by useEffect

Looking to implement a preloader that spins while the content is loading and disappears once the loading is complete. However, encountering an issue where the site gets stuck on the loading page and keeps loading infinitely. I've tried multiple soluti ...

Different varieties of TypeScript's keyof when working with objects

I am grappling with the concept of TypeScript's types when incorporating the keyof type operator on objects. Check out this example: type TypeA = { [k: number]: boolean }; type AKey = keyof TypeA; // ^? type AKey = number type TypeB = { [k: string] ...

specialized registration process with auth0 in Angular

I am attempting to enhance the user information in a single call. The process involves first signing up with a username and password on Auth0, followed by adding additional userinfo to the database during the callback phase. However, I am encountering diff ...

Tips for properly importing types from external dependencies in TypeScript

I am facing an issue with handling types in my project. The structure is such that I have packageA -> packageB-v1 -> packageC-v1, and I need to utilize a type declared in packageC-v1 within packageA. All the packages are custom-made TypeScript packa ...

TypeORM is failing to create a table upon initialization

Recently, I delved into the realm of typescript and decided to explore TypeORM for backend development. My current project involves building a CRUD API using typeORM and postgreSQL. After configuring everything initially, I ran the application only to rea ...

"Can you share a method to extract the value from a TextField component in a React hook-based Material-

Currently, I am using Material-UI within a React project and have a component set up like this: const UserDetail = (props: ListDetailProps) => { const oldpassword = useRef<TextFieldProps>(null); const newpassword = useRef<TextFieldProps ...

Ways to use DecimalPipe for rounding numbers in Angular - Up or down, your choice!

Looking to round a number up or down using DecimalPipe in Angular? By default, DecimalPipe rounds a number like this: Rounding({{value | number:'1.0-2'}}) 1.234 => 1.23 1.235 => 1.24 But what if you want to specifically round up or do ...

Failed to interpret Firebase ID token decoding

My approach involves restricting my API to only logged-in users by sending a Firebase token and attempting to verify it on the server-side, following Google's guidelines precisely as mentioned here. However, I encounter an exception that reads: Fire ...

Obtaining a customized variation of a class identified by a decorator

I am working with a class that is defined as follows: class Person { @OneToOne() pet: Animal; } Is there a method to obtain a transformed type that appears like this? (Including {propertyKey}Id: string to properties through the use of a decorator) ...

An issue has been encountered: No NgModule metadata was discovered for 'AppModule' in the ngx-rocket Metronic theme

Task List [ ] Initialize [x] Build [x] Serve [ ] Test [ ] End-to-End test [ ] Generate [ ] Add [ ] Update [ ] Lint [ ] Internationalization [ ] Run [ ] Configure [ ] Help [ ] Version [ ] Documentation Is this a regression? This issue started occurring ...

What is the method to acquire the firestore reference type in TypeScript?

Here is the code I am working with: import { DocumentReference } from '@firebase/firestore-types' export type Recipe = { author: string title: string ingredients: { quantity: number ingredient: DocumentReference["path"] ...

Creating TypeScript atom packages

Has anyone successfully implemented this before? I couldn't locate any assistance for it. If someone could provide references to documentation or existing code, that would be great. I know that Atom runs on Node and that there is a TypeScript compil ...

Error: The update-config.json file could not be located in Protractor

I recently converted my Cucumber tests to TypeScript and started running them with Protractor. When I run the tests from the command-line using the following commands: rimraf cucumber/build && tsc -p cucumber && protractor cucumber/build/p ...

Creating specific union types for a bespoke React hook

There are 4 objects with both similar and different keys. The union of these objects is used for database operations as follows -> type Objects = Food | Diary | Plan | Recipe ; A Custom Pagination Hook function usePaginate (key: string, options: Option ...

Loading and unloading an Angular 6 component

One challenge I'm facing involves creating an image modal that appears when an image is clicked. Currently, I have it set up so that the child component loads upon clicking the image. However, the issue is that it can only be clicked once and then dis ...

typescript Object that consists of properties from an array with a defined data type

I have an array consisting of strings. I am trying to transform this array into an object where each string is a property with specific attributes assigned to them. export interface SomeNumbers { name: string; value: number; } const arr = ['apple& ...

group items into ranges based on property of objects

I've been grappling with this issue for far too long. Can anyone provide guidance on how to tackle the following scenario using JavaScript? The dataset consists of objects representing a date and a specific length. I need to transform this list into a ...

I am looking to access a public method from a different component in Angular 2

Trying to access the headerExpand property from app.component is causing an error message in the console: metadata_resolver.js:559 Uncaught Error: Invalid providers for "Page1" - only instances of Provider and Type are allowed, got: [?undefined?] page1 ...