title: node.js + express , routers in separated files and middleware only before certain routes?
body: <p>I have Router dynamically generated. Routes files are in folders structure that corresponds to router path. e.g. route <code>v1/users/getUsers</code> so getUsers.js is in <code>/api/v1/users/</code> folder.</p>
  
  <p>My middle wares are in <code>/middlewares/</code> folder, and I am generating my express app  in <code>/createExpressApp.js</code></p>
  
  <p>so currently I have my authorisation middlware in <code>.use(auth)</code> just before <code>.use('/api', router)</code>
  This way it works just fine, before each route , auth is executed. However, I want to protect only certain routes. I guess I could just import my middleware in each file with a route I want to protect, but some of the routes are deep in folders and my import would be something ugly like <code>../../../middlware/auth.js</code></p>
  
  <p>Is there any clever way to avoid that kind of import ?</p>
  
  <p>Here is my router dynamic creation, I do admit I found that solution somewhere on the internet and I do understand idea but don't know where to put some extras for router such as router.all or router.use</p>
  
  <pre><code>import { sync } from 'glob'
  import { Router } from 'express'
  
  const auth = require('../middlewares/auth.js').isAuthenticated
  
  export default () =&gt; sync('**/*.js', { cwd: `${__dirname}/` })
      .map(filename =&gt; require(`./${filename}`).default)
      .filter(router =&gt; Object.getPrototypeOf(router) == Router)
      .reduce(
        (rootRouter, router) =&gt;rootRouter.use(router),
        Router({ mergeParams: true })
      )
  </code></pre>
  
  <p>so answering my own problem + answer from below using router.all ( or others from documentation). I would put it here: </p>
  
  <pre class="lang-js prettyprint-override"><code>export default () =&gt; sync('**/*.js', { cwd: `${__dirname}/` })
      .map(filename =&gt; require(`./${filename}`).default)
      .filter(router =&gt; Object.getPrototypeOf(router) == Router)
      .reduce(
        (rootRouter, router) =&gt;rootRouter
        .all('*getUsers',auth)
        .use(router)
        ,
        Router({ mergeParams: true })
      )
  </code></pre>