Anters Bear
Anters Bear

Reputation: 1956

Rerouting Firebase Hosting to Express Cloud Functions

I can't seem to configure routes to connect firebase hosting to my cloud function express app. I tried to setup as shown here but the behaviour seems to be different. I can't seem to figure out what I am doing wrong. Please send help, I'm going insane.

index.js

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

const app = require('./app');
exports.api = functions.https.onRequest(app);

app.js

const app = express();
// ...
app.use(cors());
app.use('/params', paramsRoutes);
module.exports = app;

firebase.json

{
  "hosting": {
    // ...
    "rewrites": [
      {
        "source": "/api/**",
        "function": "api"
      },
     // ...
    ]
  }
}

Upvotes: 0

Views: 242

Answers (1)

Vaidehi Jamankar
Vaidehi Jamankar

Reputation: 1346

There is appropriate documentation that lists your requirement of hosting the Cloud Functions in Firebase Hosting using a custom domain.

  • Make sure that you have the latest version of the Firebase CLI and that you've initialized Firebase Hosting.
  • Initialize Cloud Functions by running the following command from the root of your project directory: firebase init functions

Also as per documentationwe can use rewrites to serve requests for a specific firebase hosting URL to a function. To do that you need to use "/api". You don't have to add the entire URL because you are redirecting from firebase hosting. So, when you add "/api" you are indicating to redirect requests going to "PROJECT_ID.web.app/api and PROJECT_ID.firebaseapp.com/api" to the function you specified.
If you want redirect every single URL to your host to an express app in Cloud Functions, you will need to do the following:

  • Make sure there is no index.html in your public hosting folder (otherwise it will always be served with the path /).
  • Your Express routes need to exactly match the incoming URL, not just the wildcard part.

You can read more in the docs or follow this medium post for more details.
Check these links for similar implementation:

Upvotes: 1

Related Questions