daCoda
daCoda

Reputation: 3845

Firebase. How to execute function AND load webpage (hosting) with a URL

I need to execute a Firebase function AND load a page using a single URL.

e.g. URL = "localhost:5000/cars?make=hyundai&model=elantra"

  1. This URL will load the views/cars/index.html webpage.
  2. This URL will also call the loadCar() Firebase function.

...How can I achieve these two goals? (or is there a better way to achieve this - load a page AND invoke a function)


Current behaviour: It loads the page (achieve 1), but doesn't invoke the loadCar() function (doesn't achieve 2).

FYI my firebase.json:

{
"hosting": {
    "public": "functions/views",
    "rewrites": [
        {
            "source": "/cars/**",
            "function": "loadCar"
        }
    ]
}

My file directory (arrows pointing to relevant files):

File structure image

loadCar():

exports.loadCar= functions.https.onRequest((req, res) => {
    // const requestedCar = Get requested car info from URL queries.
    // Save requestedCar to Firestore DB, so it can be loaded in the html view.
    // ... etc.
    res.end();
});

Upvotes: 0

Views: 330

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317467

If you're asking if it's possible for a single Firebase Hosting URL to both load static content and trigger a function, it's not possible. It has to be either one, not both.

You could instead have some JavaScript code in the static content invoke the function through another URL. Or you could have the URL invoke the function, which returns HTML to display, in addition to performing other work. But the destination of the requested URL can only go to static content or a function, not both.

Upvotes: 1

Related Questions