Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to redirect all server requests to a function in Firebase Hosting

Trying to implement SSR with Firebase so I'm using a function to prerender each page of a React App. It's working well except the home page, so it must be either the match is wrong on the firebase redirect or possibly on the express route itself.

firebase.json

{
  "firestore": {
    "rules": "firestore.rules",
    "indexes": "firestore.indexes.json"
  },
  "functions": {
    "predeploy": [
      "npm --prefix \"$RESOURCE_DIR\" run lint"
    ]
  },
  "hosting": {
    "public": "build",
    "rewrites": [
      {
        "source": "**",
        "function": "contentServer"
      }
    ],
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ]
  }
}

contentServer.js

import * as functions from 'firebase-functions';
import * as fs from 'fs';
import * as path from 'path';

import React from 'react';
import Helmet from 'react-helmet';
import { renderToString } from 'react-dom/server';
import Server from '../browser/Server.js';

const express = require('express');

const app = express();

// might be this? Also tried /**

app.get(['**'], (request, response) => {
  const context = {};
  const location = request.url;
  console.log('Processing request for ', location);

  let appCode;
  try {
    appCode = renderToString(<Server context={context} location={location} />);
  } catch (err) {
    appCode = 'with error';
  }

  // const appState = {
  //   pageTitle: 'Hello World',
  // };

  // const preloadedState = JSON.stringify(appState).replace(/</g, '\\u003c');
  const fileName = path.join(__dirname, '../index.html');
  const htmlTemplate = fs.readFileSync(fileName, 'utf8');
  const head = Helmet.renderStatic();

  const responseString = htmlTemplate
    .replace('<div id="root"></div>', `<div id="root">${appCode}</div>`)
    .replace('<title>React App</title>', `${head.title}\n${head.link}`);
  return response.send(responseString);
});

export default functions.https.onRequest(app);

Curl

I run firebase serve --only functions,hosting

Then use curl to check the response:

curl http://localhost:5000 - does not render the home page - just the standard react page
curl http://localhost:5000/ - also does not work - just the standard react page.
curl http://localhost:5000/contact-us - works well and returns the contact us page, all other pages on the site work and trigger the function.
like image 918
Richard G Avatar asked Apr 27 '18 23:04

Richard G


Video Answer


1 Answers

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

Configure Firebase hosting in firebase.json to rewrite all urls to a function (you are currently doing this in your "hosting" block, which is good):

"rewrites": [
  {
    "source": "**",
    "function": "contentServer"
  }
]

Write a Cloud Function exported with the same name as the function in the rewrite, and attach an express app that handles the route wildcarded with *. In index.js in your functions folder, minimally:

const functions = require('firebase-functions')
const express = require('express')

const app = express()

app.get("*", (request, response) => {
    response.send("OK")
})

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

If you run this locally with firebase serve --only hosting,functions, every path that you send to localhost:5000 will say "OK".

like image 118
Doug Stevenson Avatar answered Oct 17 '22 05:10

Doug Stevenson