[Fixed] Dynamic rendering with Firebase Functions and Firebase Hosting


I’m trying to achieve Dynamic Rendering for my react application hosted in Firebase Hosting using Firebase Function.

The idea behind it comes from this article,

What I would like to achieve is
Firebase Functions handles all the requests,
Depending on the user agent serves static content generated on the fly, otherwise serve the main application hosted in Firebase Hosting.

So far I have just changed firebase.json to redirect all the requests to my ‘app’ function instead of ‘/index.html’

    "rewrites": [
        "source": "**",
        "function": "app"

And my app function is something like

app.get('*', (req, res) => {
    // serve static content
    // serve the index of my hosted app
    res.render('/index'); // <--- how to access hosted /index.html in build ??

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

The problem I’m facing is that from the functions running in Firebase Functions I’m not able to get content from the "build" folder

I’m trying with something like

app.get('*', (req, res) => {

But that’s obviously not working,
I’m not sure what would be the best approach..

Any help/suggestion would be appreciated


res.render() accepts an absolute path, or a path relative to the views setting. In order to traverse through the filesystem properly, you need to use a module such as path.

Here’s how to move up to "build" directory from where the current JS file resides, for example:

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


app.set('views', path.join(__dirname, '..', 'build')); 

Then render your template:


Or, another way without specifying views is to directly render the template like the following samples:

res.render(path.join(__dirname, '..', 'build', 'index'));

res.render(path.join(__dirname, '..', 'build') + '/index');

Here’s a reference on how to utilize path.join().

Leave a Reply

(*) Required, Your email will not be published