Is it possible to add middleware to routes according to their specific patterns?

In my express application, I have set up various routes to handle user-related tasks.

router.route('/login').post(userCtrl.login);
router.route('/users').get(userCtrl.getAll);
router.route('/users/count').get(userCtrl.count);
router.route('/user').post(userCtrl.insert);
router.route('/user/:id').get(userCtrl.get);
router.route('/user/:id').put(userCtrl.update);
router.route('/user/:id').delete(userCtrl.delete);

Now, I want to add a middleware that will be applied to all routes starting with '/user' except for the '/login' route.

For example, I have a middleware called checkAuth that should be used for any user-specific routes but not for the /login route.

I tried to implement this using the code below, but it didn't work as expected.

router.use("/user.*", checkAuth);

Is there a way in express to configure middleware based on a specific pattern of routes?

Answer №1

In the realm of Express, you have the flexibility to utilize app.use() or router.use() by specifying a path such as:

router.use("/user", function(req, res, next) {
    console.log(req.url); 
    next();
});

This middleware will be triggered for any URL that begins with "/user". This includes variations like:

/user
/user?foo=2
/user/something
/user/1/2

If your goal is to match URLs starting with /user, use an Express wildcard like so:

router.use("/user*", function(req, res, next) {
    console.log(req.url); 
    next();
});

This setup will cover all previous examples, along with these additional ones:

/users
/users/something
/usersxyz

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

JavaScript's "for of" loop is not supported in IE 11, causing it to fail

Here is a piece of code I'm using to select and remove a d3.js node: if (d.children) { for (var child of d.children) { if (child == node) { d.children = _.without(d.children, child); update(root); ...

eliminate the common elements between two arrays in typescript/javascript

I have two lists of objects, each containing two fields: let users1 = [{ name: 'barney', uuid: 'uuid3'}, { name: 'barney', uuid: 'uuid1'}, { name: 'barney', uuid: 'uuid2 ...

Error: Access to cross-origin frame blocked for iframe located at "http://localhost:8080" when attempting to access other iframes on the page

I am currently attempting to extract and list the names of all the iframes present on a webpage for Selenium automation. The challenge lies in the fact that each iframe's name changes dynamically, necessitating a method to iterate through all of them ...

Extract the chosen option from a dropdown menu, and then transfer it to another dropdown menu with a new corresponding value

Below is a select box I currently have: <td align="center"> <select id="selectW" name="type" onChange="this.form.submit()"> <option value="select...">select</option> <option value=" ...

The infinite scroll feature on Next.js resulted in duplicating the last element during the initial fetch process

I have a project that involves fetching data from Strapi Rest API using Next.js. I am fetching and displaying cards based on the fetched content. To prevent loading all the data at once, I have implemented an infinite scroll feature using react-infinite-sc ...

What is the method for invoking a function with arguments within an HTML `<p>` element?

I am looking to display like and dislike percentages on cards. <v-card v-if="software[2] == searched || searched == ''" class="software-card" > <h3>{{ software[2] }}</h3> ...

Images are being blocked from loading due to the Content Security Policy

I recently encountered an issue with my express app where external assets were being blocked by CSP. This is a new problem for me, and I suspect it may be related to using passport.js and helmet.js for the first time within my app. Could their configuratio ...

develop a customizable component library similar to shadcn for easy installation

Currently in the process of developing a design system, I am looking for advice on creating an installable library similar to shadcn. It is important to me that the source code of the components can be easily accessed and modified within my project. Is t ...

Jest test exceeded the time limit, but the manual test was successfully executed

Having some trouble testing a nodejs function with Jest. I'm new to Jest and suspect my test structure might be the issue. The function works as expected when called manually or within the app, but encounters issues when called from a Jest test - tim ...

Is it possible for the js serialize() function to work with array field names?

One of my form fields is structured like this: <input name="cm[3]" value="0.0000"> When I send this data to a secure ajax function using the serializeData method: var formData = $(form).serialize(); console.log(formData); secureajax.securecall({ ...

One effective way to utilize await/async within the Vue mounted lifecycle hook is by

I am facing an issue where the mapGetters value is showing null in my computed property because the preferences method is not executed completely. I need to wait until the store has set the getter and setter. I have tried using async/await but it's no ...

Creating a primary index file as part of the package building process in a node environment

Currently, I have a software package that creates the following directory structure: package_name -- README.md -- package.json ---- /dist ---- /node_modules Unfortunately, this package cannot be used by consumers because it lacks an index.js file in the r ...

JavaScript implementation of Twitter OAuth authentication

I searched far and wide for a strong example of a JQuery ajax call to authenticate a user on Twitter using their OAuth method. I carefully followed the instructions multiple times and this is what I've managed to put together so far. Currently, I am f ...

Swap the displayed text in a textbox within an HTML5 document

Is there a way to replace specific text in an HTML5 document? Let's say the user inputs: My name is Toni. I want to change the output text "Toni" to Ani, so the final output is: "My name is Ani". This is the current code I have: <title>tex ...

How can I retrieve the Sequelize results in the form of a 2D array rather than an array of objects?

I have a situation where I am using the Sequelize query() method like this: const sequelize = new Sequelize(...); ... // IMPORTANT: Cannot modify this query const queryFromUser = "SELECT table1.colname, table2.colname FROM table1 JOIN table2 ON/*...*/ ...

Leverage React Context beyond the confines of a React component

The React Context API has impressed me, but I often find myself struggling to access it outside of a React component. Everything works smoothly within a React function or class component, but when it comes to fetching a value from the context for tasks lik ...

Preventing font loading with Content Security Policy in Node.js Helmet

I can't figure out why it allows different fonts from Google Fonts, but always blocks Material Icons and FontAwesome. I've tried various ways of including Google Fonts in the code, but nothing seems to work. I'm not sure how to correctly lis ...

Utilize jQuery to Interpret JSON data with a Customized Format

What is the best way to handle this JSON data using jQuery? {"3":[ {"project_id":27,"name":"Name1"}, {"project_id":28,"name":"Name2"}, {"project_id":29,"name":"Name3"}, {"project_id":32,"name":"Name4"} ]} ...

The code functions properly on React Webpack when running on localhost, however, it fails to work once deployed to AWS Amplify

As I work on my React.js app, I encountered an issue with hosting pdf files on Amplify. While everything runs smoothly on localhost/3000, allowing me to access and view the pdf files as desired either in a new tab or embedded with html, the same cannot be ...

add component automatically upon selection

Imagine I have a special <SelectPicker/> element that allows me to choose an option. What I am trying to figure out is how I can include another <SelectPicker/> once I have made a selection. function DynamicComponent() { const [state, setSta ...