Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting up a middleware in router.route() in nodejs (express)

what I want it to do.

 router.post('/xxxx', authorize , xxxx);

  function authorize(req, res, next)
   {
    if(xxx)
        res.send(500);
    else
     next(); 
   }

I want to check for session in each route. But since the routers are written in this way.

router.route('/xxx/xxxx').post(function(req, res) {
    // blah lah here...
    //
});

So how can I set up a middleware that will check for session and I wanted to make things a bit more generic and wanted to have a single authorize function doing a single thing instead of checking in every request.Any suggestions.

like image 467
sac Dahal Avatar asked Dec 21 '16 13:12

sac Dahal


People also ask

How do I use middleware on Route Express?

Use third-party middleware to add functionality to Express apps. Install the Node. js module for the required functionality, then load it in your app at the application level or at the router level. The following example illustrates installing and loading the cookie-parsing middleware function cookie-parser .

What is router () in Express?

The express. Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests. Multiple requests can be easily differentiated with the help of the Router() function in Express. js.

Which middleware is used to handle the routing logic in Express?

Express. js is a routing and Middleware framework for handling the different routing of the webpage and it works between the request and response cycle. Middleware gets executed after the server receives the request and before the controller actions send the response.


1 Answers

Define a middlware function before you define / include your routes, this will avoid you checking for a valid session in every route. See code below for an example on how to do this.

If some routes are public, i.e. they do not require a user to have a valid session then define these BEFORE you 'use' your middlware function

var app = require("express")();

//This is the middleware function which will be called before any routes get hit which are defined after this point, i.e. in your index.js
app.use(function (req, res, next) {

  var authorised = false;
  //Here you would check for the user being authenticated

  //Unsure how you're actually checking this, so some psuedo code below
  if (authorised) {
    //Stop the user progressing any further
    return res.status(403).send("Unauthorised!");
  }
  else {
    //Carry on with the request chain
    next();
  }
});

//Define/include your controllers

As per your comment, you have two choices with regards to having this middleware affect only some routes, see two examples below.

Option 1 - Declare your specific routes before the middleware.

app.post("/auth/signup", function (req, res, next) { ... });
app.post("/auth/forgotpassword", function (req, res, next) { ... });

//Any routes defined above this point will not have the middleware executed before they are hit.

app.use(function (req, res, next) {
    //Check for session (See the middlware function above)
    next();
});

//Any routes defined after this point will have the middlware executed before they get hit

//The middlware function will get hit before this is executed
app.get("/someauthorisedrouter", function (req, res, next) { ... });

Option 2 Define your middlware function somewhere and require it where needed

/middleware.js

module.exports = function (req, res, next) {
    //Do your session checking...
    next();
};

Now you can require it wherever you want it.

/index.js

var session_check = require("./middleware"),
    router = require("express").Router();

//No need to include the middlware on this function
router.post("/signup", function (req, res, next) {...});

//The session middleware will be invoked before the route logic is executed..
router.get("/someprivatecontent", session_check, function (req, res, next) { ... });


module.exports = router;

Hope that gives you a general idea of how you can achieve this feature.

like image 106
Lee Brindley Avatar answered Nov 13 '22 06:11

Lee Brindley