Encountering difficulty with displaying a 404 error using Cloud Functions on Firebase Hosting

I am currently facing an issue with handling a custom 404 error using Firebase Hosting and Functions. The code I have provided below works perfectly fine on localhost, but once deployed, Firebase Hosting returns a 500 error instead of the expected 404.

  • https://xxxx.web.app/myfunction/hello
    -> returns "hello world"
  • https://xxxx.web.app/myfunction/404
    -> returns a 500 error
  • http://localhost/myfunction/404 -> returns a custom 404 page

I am seeking help to identify what might be causing this unexpected behavior.

Below is the simplified code snippets for my index.js file:

const functions = require('firebase-functions');

exports.myfunction = functions.region('asia-east1').runWith({maxInstances: 2}).https.onRequest((request, response) => {
    if (request.path == '/myfunction/hello') {
        return response.send("hello world")
    }

    response.set('X-Cascade', 'PASS');
    return response.status(404).end()
});

And here is the firebase.json configuration:

{
  "functions": [
    {
      "source": "functions",
      "codebase": "default",
      "ignore": [
        "node_modules",
        ".git",
        "firebase-debug.log",
        "firebase-debug.*.log"
      ]
    }
  ],
  "hosting": {
    "public": "public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "/myfunction/*",
        "function": "myfunction",
        "region": "asia-east1"
      }
    ]
  }
}

Additional information about the file structure:

.
├── firebase.json
├── functions
│   ├── index.js
│   └── package.json
└── public
    ├── 404.html
    └── index.html

Answer №1

When looking at Firebase functions and hosting in a production environment, it's important to note that they operate on separate environments. This means that the 404.html file located in the public folder will only be effective when a browser triggers a 404 Not Found error, not when a firebase function is invoked on the server side, as explained in the documentation.

The behavior changes when using the local emulator, where the functions emulator can access the files and work correctly.

If you're working with your code, you have two options:

Option 1

You can create a custom 404.html within the functions directory and serve it to the browser like this:

Please note: I've removed X-Cascade because it's unnecessary and could lead to a 500 error as per your description.

const functions = require('firebase-functions');
 
 exports.myfunction = functions
   .region('asia-east1')
   .runWith({ maxInstances: 2 })
   .https.onRequest((request, response) => {
     if (request.path == '/myfunction/hello') {
       return response.send('hello world');
     }
 
     return response.status(404).sendFile('404.html', { root: __dirname });
   });

Option 2

Alternatively, you can specify the route in your firebase.json for a simpler approach:

  "hosting": {
    "public": "public",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "rewrites": [
      {
        "source": "/myfunction/hello",
        "function": "myfunction",
        "region": "asia-east1"
      }
    ],
  },

Then, in your cloud function, you can simplify the code like this:

const functions = require('firebase-functions');

exports.myfunction = functions
  .region('asia-east1')
  .runWith({ maxInstances: 2 })
  .https.onRequest((request, response) => {
    return response.send('hello world');
  });

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

geolocation data not being updated in isolate scope binding

I'm currently facing an issue with using isolated scope in a directive. Surprisingly, everything seems to be working perfectly fine. I have set the '=' scope on two properties and successfully bind them in my template. However, when I call m ...

The comparison between installing a JavaScript library and simply copying .js files

As I dive into the world of web development and JavaScript, I've noticed that many open-source JavaScript libraries like jqueryUI come with readme files containing installation instructions. These instructions often mention the need to install additio ...

The issue of gallery image loading with the galleryView jQuery plugin is causing problems

Hi fellow developers, I could really use some assistance. I've been working on implementing the jquery galleryview plugin for my image gallery (check out my gallery here). Unfortunately, I'm running into an issue where the gallery is not loading ...

Is there a method to access the variable name of v-model from a child component in the parent component?

In the scenario below, I am customizing a vue radio component and using the model option to retrieve the v-model value, which is expected to be a string '1'. Is there a way for me to access its variable name 'radio1' in the child compon ...

Are you curious about the array of elements in React's carousel?

I'm currently in the process of constructing a website using React, and I have a specific challenge related to the "news" section. Within this section, I have a list of three components that represent different news items. These components are housed ...

The Chart.js donut chart is not displaying as expected on the HTML page when using

My HTML code is set up to display a donut chart with database records retrieved through a PHP script. The data is successfully fetched and visible in the browser console, but the chart itself is not showing up. How can I resolve this issue? console.lo ...

Using JavaScript to Apply CSS Styles in JSF?

Is it possible to dynamically apply a CSS style to a JSF component or div using Javascript? I have been searching without any success. Below is some pseudo code: <div style="myJSStyleFunction("#{myBean.value}")"> stuff </div> The function wo ...

What causes a horizontal line to form when a user enters white space?

I have written a piece of code which seems to be causing an issue when running it. Whenever I input empty spaces, it results in creating a horizontal line. import React, { Component } from 'react'; export default class App extends Component { co ...

Creating an Organized Framework for a Website Application

In my particular case, I am utilizing an AngularJS application, although I believe this inquiry is relevant to any Single Page App. I've implemented a component structure as outlined in various resources such as this and this. Let's assume I ha ...

Exploring the world of npm packages: from publishing to utilizing them

Exploring My Module npmpublicrepo -- package.json -- test.js The contents of package.json are as follows: { "name": "npmpublicrepo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Erro ...

Protractor encounters a TypeError when attempting to navigate with Firefox version 59 due to a cyclic object value

Our team has implemented several Protractor tests for our Angular JS application. Recently, we considered upgrading the Firefox browser to version 59 while using Selenium 3.11.0. However, after the upgrade, whenever we try to use element(by. in our tests ...

Focus on the iPad3 model specifically, excluding the iPad4

I am looking to apply specific CSS that works on iPad 3, but not on iPad 4, or vice versa. Currently, I am able to target both versions by using the following code: @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and ( m ...

Unraveling dependencies in deno for debugging purposes

When working with Node + NPM, dependencies are installed in node_modules, making it easy to debug by adding debugger statements or console logs directly in the node_modules/some-pkg/some-file.js. In Deno, things are a bit more complex as dependencies are ...

Access Sharepoint from an external site

Looking for assistance with a SharePoint list containing columns for Name, Position, Office, and Salary. Upon logging in with specific credentials to the SharePoint website, I need to retrieve all items from the list and showcase them on my own website. ...

Error: The function $(...).live is not defined within the MVC framework

I included a dialog box using jQuery in my MVC form. Here is the code snippet from my View : <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></scr ...

BackboneJS struggles to redirect to .fail when an API request exceeds the timeout

I'm a newbie to backbone and I've come across some interesting code that adds Deferred to enable the use of promises. Take a look at the snippet below: getPatientInfo: function fetch(options) { var deferred = $.Deferred(); Backbone.Model.p ...

Encountering an issue with resolving the module - Material-UI

I am encountering an issue when trying to import a component from 'Material-Ui'. I am currently working with React and Webpack. My goal is to utilize the "Card" component (http://www.material-ui.com/#/components/card). The import statement for C ...

Updating the material-ui checkbox state to reflect the checked, unchecked, or indeterminate status, can be achieved in reactjs without relying on state

I am currently using Material-UI checkbox components and I have a requirement to programmatically change the state of checkboxes to be checked, unchecked, or indeterminate based on the click of another checkbox. This action needs to be applied to a list of ...

In JavaScript, you can update the class named "active" to become the active attribute for a link

My current menu uses superfish, but it lacks an active class to highlight the current page tab. To rectify this, I implemented the following JavaScript code. <script type="text/javascript"> var path = window.location.pathname.split('/'); p ...

Error with infiniteCarousel in Internet Explorer versions 7 and 8 when using jQuery

Hello everyone! I've run into a little issue with some jQuery code I'm using. It was working fine before, but after making several changes and improvements, I can't seem to figure out what the problem is. I keep getting JS errors in both IE7 ...