Code Guru
Code Guru

Reputation: 15598

how to make app.use synchronous in nodejs

I have created a nodejs app with the express framework. There are some routes and I am using passport library for authentication. Here is my login url mapping

app.post('/login', loginHandler);

and before this, I have used app.use

// middleware to use passport strategy
app.use((req: any, res: any, next: any) => {
   if (req.originalUrl == '/login') {
       passport.authenticate('local', { session: false }, (err, user) => {
             if (user) {
                req.user = user;
             }
       })(req, res, next);
   }
   next();
});

and in my loginHandler

function loginHandler(req: any, res: any) {
    console.log("user", req.user)
    if (!req.user) {
       console.log("NoUser")
    } else {
        res.redirect("/home");
}

but loginHandler method does not get user object in request object because app.use is asynchronous. How can I solve this?

Upvotes: 0

Views: 711

Answers (2)

Himanshu sharma
Himanshu sharma

Reputation: 7929

Edit your code and make this change .

// middleware to use passport strategy
app.use((req: any, res: any, next: any) => {
   if (req.originalUrl == '/login') {
       passport.authenticate('local', { session: false }, (err, user) => {
             if (user) {
                req.user = user;
             }
               next();         ////// change is here
       })(req, res, next);
   }else{
     next();
   }

});

The code is correct but you call next() synchronous way . Add next() inside the passport block will allow you to pass the req.user perfectly

Upvotes: 1

Code Guru
Code Guru

Reputation: 15598

As from the @Himanshu's answer, I need to use next() method inside the passports authenticate callback function. This works but for other requests, there still need a next() function. So the updated answer is

// middleware to use passport strategy
app.use((req: any, res: any, next: any) => {
   if (req.originalUrl == '/login') {
       passport.authenticate('local', { session: false }, (err, user) => {
             if (user) {
                req.user = user;
             }
             next();
       })(req, res, next);
   } else { 
       next();
   }

});

Upvotes: 0

Related Questions