How can I retrieve the name of the upcoming middleware function in Express.JS?

Hey there, I'm currently facing a challenge with retrieving the names of middleware functions in a specific request route. Let's consider the code snippet below as an example:

const authorizeRoute = (req,res,next) => {
  let nextFunctionName = SomeFunctionToRetrieveTheNameOfTheNextMiddlewareToBeCalled()
  if (isUserAuthorized(req.user.id, nextFunctionName)) next()
}

app.use(authorizeRoute)
app.get("/users", controller.getUsers)
app.get("/users/:id/posts", controller.getUserPosts)

In this scenario, I am aiming for the authorizeRoute middleware to identify the name of the subsequent middleware function within the stack.

For instance, when a GET request is made to "/users", I wish for the nextFunctionName to hold the value of "getUsers" or "controller.getUsers" or something similar. Similarly, for a GET "/users/:id/posts" request, I expect the nextFunctionName to be set as "getUserPosts" or equivalent.

Could you provide guidance on how to achieve this? I am relatively new to Express, Node.js, and JavaScript, so any assistance would be greatly appreciated.

I am aware that it is feasible to obtain the function name as a string in JavaScript.

someFunction.name // returns "someFunction" as a string

Hence, I believe that solving this challenge is possible. I just lack the knowledge of the precise approach to take.

P.S. While there may be alternate methods to attain the desired outcome, the example shared above resonates closely with my current requirements.

Answer №1

After some investigation, I discovered the solution. Interestingly, I found that placing the middleware to retrieve the stack for a route using app.use was not effective. However, when the middleware is included among the handlers for the route, it functions as intended.

const RetrieveLastMiddlewareName = (req) => {
  let stack = req.route.stack
  return stack[stack.length-1].name
}

const authorizeRoute = (req,res,next) => {
  let nextFunctionName = RetrieveLastMiddlewareName(req)
  if (isUserAuthorized(req.user.id, nextFunctionName)) next()
}

app.get("/users", authorizeRoute, controller.getUsers)
app.get("/users/:id/posts", authorizeRoute, controller.getUserPosts)

It's ironic that the answer was right in front of me all along 😐

Answer №2

To keep things simple, it might be better to avoid dynamic solutions. Consider this approach:

const newFunction = (user)=> {
    // perform actions synchronously
}

const authorizeUser = (req, res, next) => {

  if (isUserAuthorized(req.user?.id)){
      newFunction(req.user)
    }

   next()
}

If simplicity is your goal, perhaps the following would be more suitable:

const newFunction = (user, next)=> {
    // additional functionality here
    next();
}

const authorizeUser = (user, next) => {
  if (isUserAuthorized(user.id)){
      newFunction(user, next); // invoke with next callback
    } else {
      next()
    }
  
}

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

Unraveling the Enigma of Event Handlers: Mastering the Organization of a Sprawling jQuery File within an AJAX

I've created a web application that heavily relies on AJAX and jQuery for DOM manipulation and making AJAX requests. However, I'm facing a problem with my JavaScript file: The issue is that my JavaScript file consists of a huge collection of eve ...

Having trouble with installing the most recent versions of React App dependencies

After cloning a project from GitHub, I attempted to install dependencies using npm install, but encountered an error: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email ...

Error: Vue.js application requires the "original" argument to be a Function type

I am facing an issue when trying to call a soap webservice using the 'soap' module in my Vue SPA. Strangely, I encounter an error just by importing the module. Despite my extensive search efforts, I have not been able to find a solution yet. Her ...

The values in my array are causing it to output NAN

I'm currently working on a program that aims to combine a variable number of one-row matrices with varying lengths. The goal is to add the elements of each matrix together, where element one of array one adds to element one of array two, and so forth. ...

Is the utilization of react-router for developing 'single-page applications' causing a depletion of server resources?

Hello, I am relatively new to the world of web development and would appreciate guidance on any misunderstandings I may have. Currently, I am immersing myself in learning the MERN stack. For my practice project, I am aiming to create a simple two-page webs ...

ReactJs: Tweaking Padding in Material-UI Table

After inheriting this fullstack app, I noticed that the original developers had incorporated a component to generate tables for the webpage. However, there is an issue with the padding on all the cells being too large. Through Chrome developer tools, I di ...

Encountering a Typescript error while attempting to remove an event that has a FormEvent type

Struggling to remove an event listener in Typescript due to a mismatch between the expected type EventListenerOrEventListenerObject and the actual type of FormEvent: private saveHighScore (event: React.FormEvent<HTMLInputElement>) { This is how I t ...

Upon logging in to the first HTML page, the user will be automatically redirected to the second HTML page while passing values

Is there a way to automatically redirect users to Login2.html when selecting "TEAM" in the dropdown on Login1.html, using the values entered in Login1.html? Similarly, can we redirect them to the Premium page when they select "Premium"? I need a solution u ...

Implementing a click event on a selection option – tips and tricks

When I want to select an option, I can use the following script: Javascript $("#practice-area optgroup option").click(function(){ // insert your function here }); HTML <select name="practice-area" id="practice-area"> <option value="0">S ...

When the page initially loads, the block appears on top of the upper block and remains in place after the page is refreshed

Upon initial loading, the block appears on top of another block but remains fixed upon page refresh. The same issue occurs in the mobile version of the site and occasionally displays correctly. The website is built on WordPress and optimized using Page Spe ...

Designing personalized visualizations using elasticsearch

After setting up ELK tools, I have a desire to extract data from Elasticsearch and generate my own graphs without relying on Kibana. I've heard about tools like elasticsearch.js, but I'm unsure how to begin using it. What steps should I take in o ...

React hook dom and material-ui FormControlLabel are causing a checkbox input to return an empty string instead of the expected true/false value

I am currently working on displaying the values returned from a form, specifically focusing on the Checkbox section. <FormControlLabel control={<Checkbox {...register('remember')} name="remember" color="primary" defaultV ...

bootstrap-vue tabs - reveal specific tab content based on URL anchor tag

For my SPA, I am utilizing bootstrap-vue and currently working on a page where nested content needs to be placed within b-tabs. If given a URL with an anchor (e.g. www.mydomain.com/page123#tab-3), the goal is to display the content under Tab 3. Query: Ho ...

Having difficulty adjusting the width of a div element

I've been struggling to adjust the width of the div assigned with the colors class, whether in percentage or pixels. var colors = ["RED", "GREEN", "BLUE", "YELLOW", "PURPLE"]; for (var h = 0; h <= 4; h++) { for (var i = 0; i <= colors.lengt ...

SailsJS fails to transpile Bootstrap.js in a timely manner

In my backend development with Sails JS, I am utilizing ES6/7 and have created a class to handle background tasks. After reading a post on StackOverflow (link), it was recommended to initiate background tasks in config/bootstrap.js. Following this advice, ...

Trouble with the display none function

I am trying to achieve the following: If my shopping cart is empty, I want another div to display over the top of it. Instead of seeing the cart, users should see a message saying 'your cart is empty'. Currently, I have set the other div to dis ...

How can we determine in JavaScript whether a certain parameter constitutes a square number?

I've developed a function that can determine whether a given parameter is a square number or not. For more information on square numbers, check out this link: https://en.wikipedia.org/?title=Square_number If the input is a square number, it will ret ...

NPM rimraf - proceed with the execution even if directories are not found (do not halt with exit code 1)

My npm script is set up to run a series of synchronous commands, starting with npm run clean:install". Here is the sequence: "install:all": "npm install && bower install", "clean": "npm run rimraf -- node_modules doc typings coverage wwwroot bow ...

Storing the selected value from a dropdown box in PHP

Can anyone help me with echoing the $row['price'] based on the user's GPU selection? Your input is greatly appreciated! #adding more content to meet word count requirements. <div id="content"> <table border="1" style="width: ...

Tips for adjusting the alignment of the Vuetify component "VDatePicker" based on the position of its parent component on the screen

Currently, I am utilizing the VMenu component from Vuetify which contains another Vuetify component called VDatePicker. The issue arises when clicking on a text field triggers the appearance of the calendar (VDatePicker). Normally, the VDatePicker componen ...