Firebase Hosting with dynamic cloud functions rewrites

前端 未结 3 1410
忘了有多久
忘了有多久 2020-12-05 02:57

I have an express.js based cloud functions app on firebase in a function named api. To use a custom domain, I\'m trying to use Firebase Hosting rewrites to rout

3条回答
  •  醉梦人生
    2020-12-05 03:52

    What seems to be the main issue is that this:

    {
        "source": "/api",
        "function": "api"
    }
    

    is actually rewriting to https://my-firebase-app.cloudfunctions.net/api/api instead of https://my-firebase-app.cloudfunctions.net/api like you'd expect. Notice how api is repeated.

    My solution to this is to create a main function which hosts all other top-level functions:

    const functions = require('firebase-functions');
    const express = require('express');
    const app = express();
    
    app.get('/users/:userId/:userData/json', (req, res) => {
        // Do App stuff here
    }
    // A couple more app.get in the same format
    
    // Create "main" function to host all other top-level functions
    const main = express();
    main.use('/api', app);
    
    exports.main = functions.https.onRequest(main);
    

    You can now use this main function to delegate to all other functions without breaking your URL structure:

    {
        "source": "/api/**", // "**" ensures we include paths such as "/api/users/:userId"
        "function": "main"
    }
    

    And voila! You can now access all api function calls via https://my-app.firebaseapp.com/api/users/:userId/:userData just like you'd expect.

    Calling this endpoint, now rewrites to https://my-firebase-app.cloudfunctions.net/main/api which is technically correct. You can then add more top-level functions by simply adding them to your main function if you wish:

    const hooks = express();
    main.use('/hooks/, hooks);
    

提交回复
热议问题