Implement authentication verification on all child endpoints within an express router

I have an express router set up and I want only authorized users to access its routes. I am currently using passport middleware. Instead of adding a check for req.user in every endpoint, is there a more efficient way to handle this?

router.get("/", async (req, res) => {
  if (!req.user) {
    return res.sendStatus(401).send({ message: "Unauthorized" });
  }
  //logic 
  res.sendStatus(200).send({message: "OK"})
});

Answer №1

To streamline the functionality, create a "middleware" component and link it to each route of a router using router.use():

function authenticationMiddleware (req, res, next) {  
  if (!req.user) {
    return res.status(401).send({ message: "Unauthorized" });
  }
  next();
}

router.use(authenticationMiddleware);

router.get("/", async (req, res) => {
  //logic 
  res.status(200).send({message: "OK"})
});

In this scenario, ensure that the authenticationMiddleware is mounted after the Passport middleware to avoid rejecting all requests upfront.

Find more information about middleware here: https://expressjs.com/en/guide/using-middleware.html

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

Observing the Transformation When Employing *ngIf or *ngSwitchCase in Angular 2

Can someone lend a hand? I've run into an issue where my custom JavaScript function is not working after using *ngIf or *ngSwitchCase to change the view. Any suggestions on how to resolve this would be greatly appreciated. ...

Unable to execute JavaScript function by clicking

I've tried everything, but I can't seem to change the button text when selecting an item in the "Requirements" dropdown. You can view the issue on this site. Located at the bottom of the page is the "Requirements" dropdown. Each item has an oncl ...

Guide on navigating to a different page following a successful Google Sign In within React18

I'm facing an issue with redirection after signing in with Google on my React 18 project. Despite successfully logging in, the page does not redirect as expected. Below is a snippet of my Login.jsx file where the Google login functionality is implemen ...

Struggling to get the findAndModify or Update functions to work properly in MongoDB. Despite fetching the desired data from my ajax call, I am unable to make any changes in the database

Here is the ajax code snippet: $(function () { $("#upvoteClick").click(function () { $.ajax({ type:"POST", data: {upvote: 2}, dataType: 'json', url:"http://localhost:9000/api/upvote" }).success(functi ...

Executing multiple MySQL queries in sequence using Express in a Node.js environment

I've written the code below, which includes a post request that runs 2 queries along with other operations: router.post('/', (req, res) => { dbController.query( "SELECT * FROM users WHERE username = 'myUserName' ...

Array-based input validation

Is there a way to validate an input field against a list of strings in an array without using custom directives or patterns? For example, if the array contains town, city, and house, then typing any of those words should result in a validation failure. An ...

I'm new to Angular and I'm wondering how to close the panel by clicking on the 'x' button and also by clicking on the screen. Can anyone help me with this

Below is the HTML code I use for my button: <button class="btn btn-outlined " ng-click="vm.showCommentBox1()">Notify All</button> <div class="comment-box custom saveAll" ng-if=""><div class="panel panel-default"> ...

Facing an issue with the format.js not functioning properly in Rails version 6.1.3

styles.css @import url("https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap"); body { font-family: 'Roboto', sans-serif; color: #333; } .wrapper { max-width: 960px; margin: 0 auto; } button { background ...

Steps to create a clickable button wrapper label in React

Contained within the components below: <CheckboxGroupLabel htmlFor={option.label}> <FormCheckbox onClick={() => onChange} key={option.label} defaultChecked={defaultChecked} {...rest} /> {option.value} ...

What is the best way to use Jquery to enclose a portion of a paragraph text within a

How can I wrap the content inside a span that comes after another span, inside a paragraph and a new span? To further illustrate this, consider the following example: <p>foo <span>bar</span> baz</p> The desired outcome is: <p& ...

Lack of Typescript 2.1 and Angular 2 type definitions with browserify

` vscode 1.7 Typescript 2.1.1 Angular 2 latest package.json "dependencies": { "@angular/common": "^2.2.4", "@angular/compiler": "^2.2.4", "@angular/core": "^2.2.4", "@angular/platform-browser": "^2.2.4", "@angular/platform-browser-dyna ...

Switch out the arrow icon in the dropdown menu with an SVG graphic

Looking for a way to customize the dropdown caret in a semantic-ui-react component? Here's how it currently appears: https://i.sstatic.net/GpvfC.png <Dropdown className="hello-dropdown" placeholder="Comapany" onChange={th ...

Monitor changes in the ID attribute and ng-model using $watchCollection

My goal is to utilize the $watchCollection feature in my directive to monitor two specific elements. The first element is the ng-model. The second element is the id attribute. I have successfully implemented separate watches for each of them. retur ...

Having trouble with the `npm start` command while working with react.js?

Currently, I am in the process of setting up React.js. To achieve this, I executed npm install -g create-react-app followed by create-react-app my-app. Afterward, I proceeded to run the npm start command but encountered the error displayed below. https:// ...

What is the process for obtaining the Tag from a React Component?

Not the HTML DOM element tag, the JSX tag, the react class name. As I work on creating an editor, adding items to the canvas array requires me to check and call the appropriate method based on what is being added. A simplified version of my idea: changeS ...

Obtaining JSON information within the AngularJS Scope

I am delving into the world of AngularJS for the first time and trying to understand it by following this example: http://jsfiddle.net/SAWsA/11/ After successfully acquiring data in JSON format, I encountered no issues. Here is a snippet of the JSON data: ...

What is the best way to incorporate new data into localstorage in a React application?

My attempt to implement and add data into local storage has not been successful as it keeps updating the old data instead of adding new ones. Can someone please explain how to store an array of objects entered by a user in local storage using React JS? ...

What is the process for retrieving paginated data from the store or fetching new data from an API service within an Angular 2 application using ngrx-effects?

After coming across this insightful question and answer about the structure of paginated data in a redux store, I found myself pondering how to implement similar principles using ngrx/store in an angular 2 application. { entities: { users: { 1 ...

Instructions for removing a class using the onclick event in JavaScript

Is there a way to make it so that pressing a button will display a specific class, and if another button is pressed, the previous class is removed and a new one is shown? Thank you for your assistance. function myFunction() { document.getElementById ...

When using the Google API load callback, the Angular(4) router does not actually replace routes; instead, it stacks them up each time

I've been attempting to implement Google Authentication in my Angular 4 application. I have successfully loaded the Google platform.js and api.js in my index.html file. When I click on the login button, this is what I have coded: gapi.load('auth ...