2

For the NodeJS application we are developing, I want to process cookies and also check the role of users for each request. I have implemented this using filters when I was coding for Tomcat Servlets, how do I implement similar architecture when coding for NodeJS?

user2020498
  • 135
  • 1
  • 8
  • See [this other answer](http://stackoverflow.com/a/23980562/697630) explaining Express middleware and how the compare to Java filters. – Edwin Dalorzo Aug 17 '14 at 05:57

2 Answers2

5

The Node equivalent of Servlet filters is Connect/Express middlewares, which have access to the request and response objects, can set headers on the response and decide whether to forward request to the next middleware in the chain of middlewares.

Just as the doFilter method is invoked with 3 arguments, a middleware is also invoked with 3 arguments, but instead of calling filterChain.doFilter to forward the request, you call the next callback. The results of not calling the next callback is the same as not calling filterChain.doFilter(): they'll both block the request unless the response is ended.

public void doFilter(ServletRequest request, ServletResponse response, 
                     FilterChain chain) {
   if(isAuthorised(request) chain.doFilter(request, response);
}

function aMiddleware (req, res, next/*filterChain*/) {
  if(isAuthorised(req)) next();
}
c.P.u1
  • 16,664
  • 6
  • 46
  • 41
2

Assuming you use express, express middleware is similar to filters:

http://expressjs.com/api.html#middleware

But, if you are looking specifically for auth, Passport is a more complete solution: http://passportjs.org/guide/

7zark7
  • 10,015
  • 5
  • 39
  • 54
  • Can I set req.params in router.use? For example, when I set req.params.usertype = 'type1' and try to access the parameter using req.usertype in router.get, I see that req.usertype is undefined. – user2020498 Aug 17 '14 at 13:33
  • does the control come back to middle ware after that route's execution complete? like java filter? No right? – subject-q Apr 04 '19 at 14:02