I have a firebase hosted website and I am trying to redirect the user from alternative domains in which the site is hosted (i.e. example.com, https://example.com, https://example.firebaseapp.com) to the canonical url, which is https://www.example.com.
However, it seems that the firebase function isn't working, and may not even be running consistently.
I reloaded the website several times after 8pm, however, the only logging of the function was at 7:47. Furthermore, it did not have any of the console.log statements that I expected.
I deployed my code using firebase deploy so both the functions and the edited firebase.json file should be up-to-date.
Anyone know a) why the function isn't running consistently upon reloading the website and b) why the function isn't working (if I navigate to to our website at the non-canonical URL, I will not be redirected at all).
For reference, the code is as follows (website name has been changed in the question for confidentiality):
functions/index.ts
const functions = require('firebase-functions');
const express = require('express');
const url = require('url');
import type { Request, Response } from 'express';
const app = express();
// Allowed domains
let domains = ['localhost:3000', 'https://exapmle.com', 'https://example.firebaseapp.com'];
// Base URL to redirect to
let baseurl = 'https://www.exampe.com/';
// Redirect middleware
app.use((req: Request, res: Response, next: any) => {
console.log("testing testing");
console.log('headers', req.headers['x-forwarded-host']);
console.log('domains: ', domains);
if (!domains.includes(req.headers['x-forwarded-host'] as string)) {
console.log('redirecting')
return res.status(301).redirect(url.resolve(baseurl, req.path.replace(/^\/+/, "")));
}
return next();
});
// Export redirect function
exports.redirectFunc = functions.https.onRequest(app);
firebase.json
{
...
"hosting": {
"public": "build",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html",
"function": "redirectFunc"
}
]
},
...
}
This is an attempt at implementing the solution found in this question (Redirect to Firebase Hosting custom domain).