I am hosting an app on Firebase making use of cloud functions and hosting. The former serves dynamic content in the form of a NodeJS express app with an API included, the latter serves static content such as css, javascript, etc. for my express app.
(Here is a good tutorial to get setup with express & firebase hosting)
Usually in express apps with the standard structure setup, one has a few folders created such as bin, routes, views, and public. Most of these are easily replicated in your firebase app.
Problem:
The issue is working with hosting & functions simultaneously.
Using the following index.js (in express known as app.js), I can successfully view & emulate my application locally using firebase emulators (functions, hosting, etc.)
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const express = require("express");
const engines = require("consolidate");
...
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: "https://....firebaseio.com"
});
// app routes
const usersRouter = require('./app/users');
...
const app = express();
// #Working locally only - for deplopyment, all static linkes must load resources as [hosting-domain.app.com]/css/styles.css
app.use("/public", express.static(path.join(__dirname,'../public')));
app.use(flash());
app.engine('pug', require('pug').__express)
app.set('views', __dirname + '/views');
app.set('view engine', 'pug');
// Use the createSession endpoint for login & verify each session
app.use(authenticate);
...
app.use('/user', usersRouter);
app.get('/', (req, res) => {
return res.redirect("/user/login");
});
app.get('*', (req, res, next) => {
res.render("404");
})
exports.app = functions.https.onRequest(app);
// api routes
exports.api = require('./api/api.js');
How can I serve static content successfully on firebase hosting while using firebase functions for dynamic content?
(answer follows)
