user7885981
user7885981

Reputation:

How can you host firebase functions and a single-page application?


I am working on a single-page application using React.js. My team and I are set on utilizing Firebase Hosting to the best of our abilities and are trying to deploy our application. My issue is that I am trying to deploy both the static site and functions, the only issue is that I cannot host the both of them with my current configuration. This is the firebase.json that I am using though it does not show the function at /helloWorld, only the static site.

{
  "hosting": {
    "public": "public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "/helloWorld",
        "function": "helloWorld"
      },
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

I want it to route to the helloWorld function when I go to /helloWorld, and route it to the static index.html file when I go to any route other than /helloWorld. This is an example if I were was Express.js.

const express = require('express');
const app = express();

app.get('/helloWorld', (req, res) => {
  res.send('this is a cloud function');
});

app.get('*', (req, res) => {
  res.send('this is the static site');
});


app.listen(3000);

Upvotes: 1

Views: 1049

Answers (1)

Cedric
Cedric

Reputation: 122

If I understand it well, you simply want to redirect your users to index.html when they try to reach www.yourwebiste.com/** (where ** can be anything else than helloWrold) and show helloWorld page only when they try to reach www.yourwebsite.com/helloWorld

Right?

If yes, than here's how I would do it:

firebase.json

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

There's no need to add

{
  "source": "**",
  "function": "/index.html"
}

because it's the default redirection.

Then in your js file

const express = require("express");
const redirection = express();

redirection.route('/helloWorld')
  .get(function (req, res) {
    res.send('this is my redirected page')
  })

Upvotes: 3

Related Questions