Search code examples
node.jsfirebasegoogle-cloud-functionsfirebase-hosting

Google cloud function don't get triggered


I'm trying to trigger a google cloud function when a path of my hosting web site is reached.

So, I have added this on my firebase.json

"rewrites": [
  {
    "source": "**",
    "destination": "/index.html",
    "function": "app"
  } 

here is my function called "app" :

[...]
server.get('*', (req:any,res:any) => {
 const isBot = detectBot(req.headers['user-agent']);

 if(isBot) {
     const botUrl = generateUrl(req);

     nf(`${renderUrl}/${botUrl}`)
     .then((r: { text: () => any; }) => r.text())
     .then((body: { toString: () => any; }) => {
         res.set('Cache-Control', 'public, max-age=300, s-maxage=600');
         res.set('Vary','User-Agent');
         res.send(body.toString())
     });
 } else {
    nf(`https://${appUrl}`)
    .then((r: { text: () => any; }) => r.text())
    .then((body: { toString: () => any; }) => {
        res.send(body.toString());
    });
 }


});


exports.app = functions.https.onRequest(server);

The "app" function and website are deployed but when i reach an url the "app" function don't get triggered.

Thanks in advance.


Solution

  • Your "rewrites" section isn't properly set up. You specify both a destination ("/index.html") and a function parameter. Here's an example rewrites that will direct requests to /function-url to your app function and other requests (undefined or "/foo" and "/foo/**") to your index.html:

    "rewrites": [ {
        // Serves index.html for requests to files or directories that do not exist
        "source": "**",
        "destination": "/index.html"
      }, {
        // Serves index.html for requests to both "/foo" and "/foo/**"
        // Using "/foo/**" only matches paths like "/foo/xyz", but not "/foo"
        "source": "/foo{,/**}",
        "destination": "/index.html"
      }, {
        // calls your app function for requests to "/function-url"
        "source": "/function-url",
        "function": "app"
      } ]
    

    More info on how to configure rewrites here.