Using Regular Expressions in Firebase Functions to achieve a 'Clean Path' when utilizing app.use() in Express.js

Objective: I want Express to return /register when the browser URL is http://localhost:5000/register. This seemingly simple goal is proving to be a challenge with Express.

Let's start by looking at my firebase.json:

firebase.json:

"hosting": 
    {
      "target": "store",
      "public": "store/public",
      "ignore": [
        "firebase.json",
        "**/.*",
        "**/node_modules/**"
      ],
      "rewrites": [
        {
          "source": "/app{,/**}",
          "destination": "/app/app.html"
        },
        {
          "source": "**",
          "function": "site"
        }
      ]
    }

Next, in my Firebase Functions file, index.js:

const functions = require('firebase-functions');
const express = require("express");
const site = express();

// Handling paths not starting with /app/.
site.use(/^\/(?!app).*/, function (req, res, next) {
    console.log(`req.path] = ${req.path}`);
    console.log(`req.route.path] = ${req.route.path}`);
    console.log(`req.originalUrl] = ${req.originalUrl}`);
    console.log(`req.url] = ${req.url}`);
    console.log(`req.baseUrl] = ${req.baseUrl}`);
    console.log(`site.mountpath = ${site.mountpath}`);

    next();
});

site.get("/", (req, res) => {
    res.send("Homepage");
});

site.get("/register", (req, res) => {
    res.send("Registration Page");
});

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

Here are the outputs from the console:

i  functions: Beginning execution of "site"
>  req.path] = /
>  req.route.path] = *
>  req.originalUrl] = /firebase-project-id/us-central1/site/register
>  req.url] = /
>  req.baseUrl] = /firebase-project-id/us-central1/site/register
>  site.mountpath = /

Despite various attempts resulting in similar outcomes like /, none seem to accomplish my straightforward goal of obtaining just /register without manipulating

/firebase-project-id/us-central1/site/register
. Are there any other dependable approaches that can help me achieve this? Appreciate your suggestions!

Answer №1

Regarding the solution provided by @Doug Stevenson in this post, using req.headers['x-original-url'] did the trick!

Here is the output from the console:

req.headers['x-original-url'] = /login

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Refreshing an Angular datatable using promises - reload directive

I am currently using angular-datatables along with promises and everything is working smoothly. I have various actions that can be performed on each record (using angular $http resource) such as changing a status or similar tasks. However, I find that I n ...

Check if the input values are already in the array and if not, then add

Within my React application, I am displaying an Array and each entry in the Array is accompanied by an input element. These input elements are assigned a name based on the entry's ID, allowing users to enter values. To handle the changes in these inp ...

Utilizing SEO and incorporating special characters like !# in a website's URL

I came across an interesting concept about designing a website that utilizes AJAX to load each page section without compromising SEO. It involved incorporating !# in the URL, similar to the approach adopted by Twitter. However, I've been unable to loc ...

Node.js - updating the value of a exported integer variable

In my file A.js, I have defined a module-level variable called activeCount and exported it using module.exports. In another file named testA.js, I am attempting to access and modify the value of activeCount. Despite my efforts, changes made to activeCount ...

How can AngularJS focus on the last element using ng-repeat and md-focus?

, there is a code snippet that utilizes AngularJS ng-repeat directive to iterate through 'items' and 'md-autofocus' attribute to focus on the last element. The code is contained within an md-dialog with vertical scrolling functionality. ...

Implementing a JQuery modal with backend coding

I have encountered a problem in my ASP.NET code-behind where I am trying to incorporate a modal popup. Despite my efforts, I have not been able to successfully implement it. Do you have any suggestions on how I should proceed with this process? <scrip ...

Transferring Information between a Pair of Controllers

Currently, I am utilizing angular version 1.x and faced with the challenge of sharing data between two controllers. In my mainctrl, I am working with the above model. The radiotmplt.radiohead=='IRU600v3' is utilized in firstctrl. Unfortunately, ...

Gulp- Ensuring the latest versions of your javascript files

I have implemented bundling and minification for my JavaScript files using gulp. What I am aiming to achieve is that whenever I make a change in any of my files and run gulp, a new bundled and minified file with a version number is generated. For example: ...

Tips for displaying previous values when discarding changes to a record in a material-ui table

How can I prevent changes from reflecting in a material-ui table when clicking on the X icon while editing a row? Is there a way to only save the edited record on the check (_) icon instead? Any suggestions or solutions would be greatly appreciated as I am ...

What is the best method to make the first input field the focus in BootStrap?

Is there a way to prioritize the focus on the initial input element in an HTML form without specifying an ID? How to set the focus to the first input element in an HTML form independent from the id? I'm working with BootStrap and ASP.NET MVC4. De ...

Utilize Vue to access and read a file stored in the current directory

I am attempting to retrieve data from a text file that is located in the same directory as my .vue file. Unfortunately, I am encountering an issue where the content of the text file is not being displayed in both Chrome and Firefox. Instead, I am seeing th ...

Error code 12030: AJAX request status

When making an ajax XMLHttpRequest using the POST method, I am encountering a readyState of 4 with a status of 12030. It is known that 12030 is a Microsoft-specific state code indicating that the connection was not sustained. However, I have been unable to ...

determine the height of a div using jquery calculations

If a div is positioned relative and contains child divs that are positioned absolute, the parent div will have no set height. However, if the contents of the div change dynamically, there should be a way to calculate and adjust the height of the parent acc ...

"Exploring the concepts of inheritance in Typescript

I'm seeking answers regarding inheritance in TypeScript/JavaScript. Below is my base class (express controller router): abstract class BaseCtrl { abstract model; // Get all getAll = (req, res) => { this.model.find({}, (err, docs) => ...

The onClick functionality for the IconComponent (dropdown-arrow) in React Material UI is not functioning properly when selecting

I have encountered a problem in my code snippet. The issue arises when I attempt to open the Select component by clicking on IconComponent(dropdown-arrow). <Select IconComponent={() => ( <ExpandMore className="dropdown-arrow" /> )} ...

Encountering an issue in React: Uncaught ReferenceError - require function not recognized

I am currently working on a project that utilizes both react and node (express). When I include react using src="https://unpkg.com/react@16/umd/react.development.js", everything works fine with JSX in the project. However, when I attempt to import like thi ...

Guide to updating a particular field in an object inside an array in MongoDB

Task Manager program: React, Firebase Exploring the creation of a function that updates specific fields from a request within an array of objects Data Structure in Database https://i.sstatic.net/pbYoh.png const updateTask = async (req, res) => { try ...

Guide on securely presenting an HTTP-only cookie as a bearer token, without the use of Angular.JS

Can a JWT be securely stored as an HTTP-only cookie and also used as a bearer token without relying on Angular.JS? I believe this could be achievable, as Angular.JS offers similar features (although I'm not sure if they use an HTTP-only cookie to sto ...

Problem encountered with JavaScript getter on iOS 5

While implementing JavaScript getters in my iPad-optimized website, everything was working perfectly until I updated to iOS 5. Suddenly, the site stopped functioning properly. After thorough investigation, I discovered the root cause of the issue. I have ...

What methods are available to test my website across different browsers such as outdated versions of Internet Explorer like IE8?

Currently, I am working on Chrome with Windows 7 OS installed. However, Windows 7 does not support Internet Explorer 8. This is causing issues when trying to view my web pages in the IE8 version and older. How can I resolve this problem? I have attempted ...