giovanni
giovanni

Reputation: 388

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, https://dev.to/burhanahmeed/dynamic-rendering-simple-solution-for-spa-when-shared-on-social-media-amd

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) => {
  if(isBot()){
    // serve static content
  }else{
    // 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) => {
  res.render('../build/index');
});

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

Any help/suggestion would be appreciated

Upvotes: 2

Views: 696

Answers (1)

Donnald Cucharo
Donnald Cucharo

Reputation: 4126

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:

res.render('index');

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().

Upvotes: 3

Related Questions