Oscar Franco
Oscar Franco

Reputation: 6260

Google Cloud Function behind Firebase Hosting, JSON response is converted into HTML, how to disable such behavior?

We are using Firebase in our project, we have a bunch of cloud functions, to which we have enabled access via Firebase Hosting.

In our 'firebase.json':

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

And this works fine when we query the endpoints, however, the hosting server seems to be messing with the response from our back-end, instead of returning raw json (which we need to deploy/show errors), it returns a html encoded response.

enter image description here

And the headers in the response: enter image description here

You can see the Content-Type header is returning html... All of this is just really confusing behavior because of all the Firebase magic... is there any way to turn off this behavior? I've gone through the documentation and cannot find anything, I need the responses of my cloud-functions to be left as-is.

Upvotes: 0

Views: 313

Answers (2)

Dharmaraj
Dharmaraj

Reputation: 50930

As per MDN, "Content-Type header tells the client what the content type of the returned content actually is" You can specify the content-type for each endpoint separately or use Express Middlewares. Middleware functions are executed before each endpoint in the route. For example, in your route /api, you can do:

app.use("/api", function (_, res, next) {
  //The follow code will be executed only for the /api route
  res.header('Content-Type', 'application/json')
  next() //goes to the next middleware or the route
})

Upvotes: 1

Oscar Franco
Oscar Franco

Reputation: 6260

Found the problem, we were not setting any Content-Type header in our Firebase Functions at all, if you set them Firebase Hosting respects them.

In Express you can set a global header:

app.use(function (_, res, next) {
  res.header('Content-Type', 'application/json')
  next()
})

Just be careful you are not breaking other endpoints.

Upvotes: 0

Related Questions