Is it ok for an Express.js middleware to rely on a previous middleware in the chain?What is Node.js' Connect, Express and “middleware”?How to get GET (query string) variables in Express.js on Node.js?Express.js req.body undefinedEnabling HTTPS on express.jsWhat is Express.js?Node.js / Express.js - How does app.router work?install a previous version of a packageExpress.js - app.listen vs server.listenHow do I access previous promise results in a .then() chain?Express.js middleware extra (fourth) argument

Got a new frameset, don't know why I need this split ring collar?

Operator currying: how to convert f[a,b][c,d] to a+c,b+d?

Fibonacci sequence and other metallic sequences emerged in the form of fractions

Do my partner and son need an SSN to be dependents on my taxes?

How to write a nice frame challenge?

...and then she held the gun

Fantasy game inventory — Ch. 5 Automate the Boring Stuff

What is this plant I saw for sale at a Romanian farmer's market?

How to use random to choose colors

How did the European Union reach the figure of 3% as a maximum allowed deficit?

Justifying Affordable Bespoke Spaceships

What does this Swiss black on yellow rectangular traffic sign with a symbol looking like a dart mean?

Digital signature that is only verifiable by one specific person

Expand command in an argument before the main command

How much steel armor can you wear and still be able to swim?

Why we can't jump without bending our knees?

Checking if argument is a floating point without breaking on control sequences in argument

Co-worker is now managing my team. Does this mean that I'm being demoted?

How to sort human readable size

Credit card validation in C

Does knowing the surface area of all faces uniquely determine a tetrahedron?

Is the infant mortality rate among African-American babies in Youngstown, Ohio greater than that of babies in Iran?

How to ask if I can mow my neighbor's lawn

How did Frodo know where the Bree village was?



Is it ok for an Express.js middleware to rely on a previous middleware in the chain?


What is Node.js' Connect, Express and “middleware”?How to get GET (query string) variables in Express.js on Node.js?Express.js req.body undefinedEnabling HTTPS on express.jsWhat is Express.js?Node.js / Express.js - How does app.router work?install a previous version of a packageExpress.js - app.listen vs server.listenHow do I access previous promise results in a .then() chain?Express.js middleware extra (fourth) argument






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















Let's say I have a POST request in my API POST /api/comments where I create a comment. Comments are received in array tree structure (each comment has a children property, which can have subcomments). I have multiple "events" that occur before response is sent.



I can put all the required code into one middleware function like this.



function postComments(req, res, next) 
// handle general authentication
if (!isAuthenticated())
next("not authenticated ...");


// handle more specific authentication (ex. admin)
if (!isAdmin())
next("not admin ...")


// validate req.body.comments so that each comment has allowed form
if (!areCommentsValid())
next("not valid ...");


// modify comments for database insertion
const modifiedComments = modifyComments();

// database insertion
db.insert(modifiedComments)

res.sendStatus(201);



In above example general auth and admin authentication can be used in multiple routes and next middlewares are not relying on them, code is still working. So code those 2 makes sense.



In this example my middleware does multiple things.



What I thought I could do was split the following code into multiple middleware.



function userAuth(req, res, next) 
// handle user authentication


function adminAuth(req, res, next)
// handle admin auth


function validateComments(req, res, next)
// handle req.body.comments validation


function modifyComments(req, res, next)
// modify comments
// req.commentsForDb = modifiedComments;


function postComments(req, res, next)
// insert req.commentsForDb into database



So now I split my middleware into 4 different middlewares, but the problem is middlewares depend on each other.



postComments requires modifyComments to set req.commentsForDb, modifyComments requires validateComments etc.



Which is the preferred method?










share|improve this question






























    1















    Let's say I have a POST request in my API POST /api/comments where I create a comment. Comments are received in array tree structure (each comment has a children property, which can have subcomments). I have multiple "events" that occur before response is sent.



    I can put all the required code into one middleware function like this.



    function postComments(req, res, next) 
    // handle general authentication
    if (!isAuthenticated())
    next("not authenticated ...");


    // handle more specific authentication (ex. admin)
    if (!isAdmin())
    next("not admin ...")


    // validate req.body.comments so that each comment has allowed form
    if (!areCommentsValid())
    next("not valid ...");


    // modify comments for database insertion
    const modifiedComments = modifyComments();

    // database insertion
    db.insert(modifiedComments)

    res.sendStatus(201);



    In above example general auth and admin authentication can be used in multiple routes and next middlewares are not relying on them, code is still working. So code those 2 makes sense.



    In this example my middleware does multiple things.



    What I thought I could do was split the following code into multiple middleware.



    function userAuth(req, res, next) 
    // handle user authentication


    function adminAuth(req, res, next)
    // handle admin auth


    function validateComments(req, res, next)
    // handle req.body.comments validation


    function modifyComments(req, res, next)
    // modify comments
    // req.commentsForDb = modifiedComments;


    function postComments(req, res, next)
    // insert req.commentsForDb into database



    So now I split my middleware into 4 different middlewares, but the problem is middlewares depend on each other.



    postComments requires modifyComments to set req.commentsForDb, modifyComments requires validateComments etc.



    Which is the preferred method?










    share|improve this question


























      1












      1








      1








      Let's say I have a POST request in my API POST /api/comments where I create a comment. Comments are received in array tree structure (each comment has a children property, which can have subcomments). I have multiple "events" that occur before response is sent.



      I can put all the required code into one middleware function like this.



      function postComments(req, res, next) 
      // handle general authentication
      if (!isAuthenticated())
      next("not authenticated ...");


      // handle more specific authentication (ex. admin)
      if (!isAdmin())
      next("not admin ...")


      // validate req.body.comments so that each comment has allowed form
      if (!areCommentsValid())
      next("not valid ...");


      // modify comments for database insertion
      const modifiedComments = modifyComments();

      // database insertion
      db.insert(modifiedComments)

      res.sendStatus(201);



      In above example general auth and admin authentication can be used in multiple routes and next middlewares are not relying on them, code is still working. So code those 2 makes sense.



      In this example my middleware does multiple things.



      What I thought I could do was split the following code into multiple middleware.



      function userAuth(req, res, next) 
      // handle user authentication


      function adminAuth(req, res, next)
      // handle admin auth


      function validateComments(req, res, next)
      // handle req.body.comments validation


      function modifyComments(req, res, next)
      // modify comments
      // req.commentsForDb = modifiedComments;


      function postComments(req, res, next)
      // insert req.commentsForDb into database



      So now I split my middleware into 4 different middlewares, but the problem is middlewares depend on each other.



      postComments requires modifyComments to set req.commentsForDb, modifyComments requires validateComments etc.



      Which is the preferred method?










      share|improve this question
















      Let's say I have a POST request in my API POST /api/comments where I create a comment. Comments are received in array tree structure (each comment has a children property, which can have subcomments). I have multiple "events" that occur before response is sent.



      I can put all the required code into one middleware function like this.



      function postComments(req, res, next) 
      // handle general authentication
      if (!isAuthenticated())
      next("not authenticated ...");


      // handle more specific authentication (ex. admin)
      if (!isAdmin())
      next("not admin ...")


      // validate req.body.comments so that each comment has allowed form
      if (!areCommentsValid())
      next("not valid ...");


      // modify comments for database insertion
      const modifiedComments = modifyComments();

      // database insertion
      db.insert(modifiedComments)

      res.sendStatus(201);



      In above example general auth and admin authentication can be used in multiple routes and next middlewares are not relying on them, code is still working. So code those 2 makes sense.



      In this example my middleware does multiple things.



      What I thought I could do was split the following code into multiple middleware.



      function userAuth(req, res, next) 
      // handle user authentication


      function adminAuth(req, res, next)
      // handle admin auth


      function validateComments(req, res, next)
      // handle req.body.comments validation


      function modifyComments(req, res, next)
      // modify comments
      // req.commentsForDb = modifiedComments;


      function postComments(req, res, next)
      // insert req.commentsForDb into database



      So now I split my middleware into 4 different middlewares, but the problem is middlewares depend on each other.



      postComments requires modifyComments to set req.commentsForDb, modifyComments requires validateComments etc.



      Which is the preferred method?







      javascript node.js express






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 28 at 21:53









      marc_s

      593k13311361279




      593k13311361279










      asked Mar 25 at 4:58









      user3366345user3366345

      881210




      881210






















          1 Answer
          1






          active

          oldest

          votes


















          2














          It's perfectly valid and it is actually the way middleware are intended to be used.
          As long as you properly call next with an error code when something goes wrong in a middleware where you should stop forwarding to the next one.



          The added value here is that you can reuse your middlewares in many different routes. Another thing you can do, is a middleware closure generator, for example an auth middleware based on the role:



          function auth(role) 
          return function(req, res, next)
          // get my user
          // ...
          // check user role
          if user.role != role
          return next(new Error("Auth failed"))

          return next()



          // this route is for admins
          app.get(
          "/foo",
          auth("admin"),
          foo
          )

          // this one for users
          app.get(
          "/bar",
          auth("user"),
          foo
          )





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55331473%2fis-it-ok-for-an-express-js-middleware-to-rely-on-a-previous-middleware-in-the-ch%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            It's perfectly valid and it is actually the way middleware are intended to be used.
            As long as you properly call next with an error code when something goes wrong in a middleware where you should stop forwarding to the next one.



            The added value here is that you can reuse your middlewares in many different routes. Another thing you can do, is a middleware closure generator, for example an auth middleware based on the role:



            function auth(role) 
            return function(req, res, next)
            // get my user
            // ...
            // check user role
            if user.role != role
            return next(new Error("Auth failed"))

            return next()



            // this route is for admins
            app.get(
            "/foo",
            auth("admin"),
            foo
            )

            // this one for users
            app.get(
            "/bar",
            auth("user"),
            foo
            )





            share|improve this answer



























              2














              It's perfectly valid and it is actually the way middleware are intended to be used.
              As long as you properly call next with an error code when something goes wrong in a middleware where you should stop forwarding to the next one.



              The added value here is that you can reuse your middlewares in many different routes. Another thing you can do, is a middleware closure generator, for example an auth middleware based on the role:



              function auth(role) 
              return function(req, res, next)
              // get my user
              // ...
              // check user role
              if user.role != role
              return next(new Error("Auth failed"))

              return next()



              // this route is for admins
              app.get(
              "/foo",
              auth("admin"),
              foo
              )

              // this one for users
              app.get(
              "/bar",
              auth("user"),
              foo
              )





              share|improve this answer

























                2












                2








                2







                It's perfectly valid and it is actually the way middleware are intended to be used.
                As long as you properly call next with an error code when something goes wrong in a middleware where you should stop forwarding to the next one.



                The added value here is that you can reuse your middlewares in many different routes. Another thing you can do, is a middleware closure generator, for example an auth middleware based on the role:



                function auth(role) 
                return function(req, res, next)
                // get my user
                // ...
                // check user role
                if user.role != role
                return next(new Error("Auth failed"))

                return next()



                // this route is for admins
                app.get(
                "/foo",
                auth("admin"),
                foo
                )

                // this one for users
                app.get(
                "/bar",
                auth("user"),
                foo
                )





                share|improve this answer













                It's perfectly valid and it is actually the way middleware are intended to be used.
                As long as you properly call next with an error code when something goes wrong in a middleware where you should stop forwarding to the next one.



                The added value here is that you can reuse your middlewares in many different routes. Another thing you can do, is a middleware closure generator, for example an auth middleware based on the role:



                function auth(role) 
                return function(req, res, next)
                // get my user
                // ...
                // check user role
                if user.role != role
                return next(new Error("Auth failed"))

                return next()



                // this route is for admins
                app.get(
                "/foo",
                auth("admin"),
                foo
                )

                // this one for users
                app.get(
                "/bar",
                auth("user"),
                foo
                )






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 25 at 5:20









                François P.François P.

                2,135716




                2,135716





























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55331473%2fis-it-ok-for-an-express-js-middleware-to-rely-on-a-previous-middleware-in-the-ch%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                    Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript