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

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현