Daniel Gabor
Daniel Gabor

Reputation: 1526

Second middleware is only called after the route method

I have 2 middleware , one that check if the user has a valid token and the second one that check if the user has permissions. The probleme is that after calling the first middleware the program is going directly inside my route method instead of calling the 2nd middleware. Here my code :

app.use(function(req, res, next) {
  checkToken(req, res, next);
  checkPermission(req, res, next);
});

app.post("/test", (req, res) => {
  console.log("route");
})

function checkToken(req, res, next){
  console.log("check token");
  if(validToken())
    next();
  else
    res.send("no valid token");
}

function checkPermission(req, res, next){
  console.log("check permission");
  if(permission())
    next();
  else
    res.send("no permission");
}

Output I get:

check token -> route -> check permission

Output that I expect :

check token -> check permission -> route

What I want my program to do is to check either if the user has a valid token and if he has permission before going inside my route method!

Is this the right way to do it ?

Upvotes: 4

Views: 113

Answers (3)

pzaenger
pzaenger

Reputation: 11992

See also Writing middleware for use in Express apps for a better understanding how middleware work.

/* Check token */
function checkToken(req, res, next) {
  console.log("check token");
  if(validToken())
    next();
  else
    res.send("no valid token");
}

/* Check permission */
function checkPermission(req, res, next) {
  console.log("check permission");
  if(permission())
    next();
  else
    res.send("no permission");
}

/* Calling the middleware in right order */
app.use(checkToken, checkPermission, (req, res, next) => {
  next();
});

/* Finally our route */
app.post("/test", (req, res) => {
  console.log("route");
});

Upvotes: 1

Janith
Janith

Reputation: 2918

Each express middleware is given one next callback to trigger the next middleware, but here you are calling two functions inside the middleware which calls next in each method. You have to refactor your code like this,

app.use(checkToken);  // <== first middleware
app.use(checkPermission) // <== Second middleware

app.post("/test", (req, res) => {
    console.log("route");
})

function checkToken(req, res, next) {
    console.log("check token");
    if (validToken())
        next();
    else
        res.send("no valid token");
}

function checkPermission(req, res, next) {
    console.log("check permission");
    if (permission())
        next();
    else
        res.send("no permission");
}

Upvotes: 1

Lemix
Lemix

Reputation: 2960

app.use(checkToken);
app.use(checkPermission);

app.post("/test", (req, res) => {
  console.log("route");
});
...

Upvotes: 2

Related Questions