title: ExpressJS: Adding routes dynamically at runtime
body: <p>I want to be able to add new routes at runtime without restarting the server with NodeJS &amp; ExpressJS. I made a similiar approach like in this article: <a href="https://alexanderzeitler.com/articles/expressjs-dynamic-runtime-routing/" rel="nofollow noreferrer">https://alexanderzeitler.com/articles/expressjs-dynamic-runtime-routing/</a><br/>Technically I'm able to add new files and logic at runtime likewise in the article, but the problem is that when no api route was matched I'll send a 404 JSON respond (as it is supposed to be).<br><br>I think the problem that I'm having is that my dynamically created routes are never reached, because static routes have priority over dynamically created routes. This means that the created routes will be mounted after error handling and therefore will never be reached. My Code in <strong>app.js</strong><br></p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>...
  
  // Routes
  app.use('/api/products', productRoutes);
  app.use('/api/users', userRoutes);
  
  ...
  
  /* This is where the dynamically created routes should be mounted */
  
  // Error handling
  app.use((req, res, next) =&gt; {
      const err = new Error('Not found');
      err.status = 404;
      next(err);
  });
  
  app.use((err, req, res, next) =&gt; {
      res.status(err.status || 500).json({error: {message: err.message}});
  });
  
  /* This is where the dynamic routes are mounted */
  
  module.exports = app;</code></pre>
  </div>
  </div>
  </p>
  <p>When I comment out the error handling I'm able to reach the routes which I created during runtime whereas with error handling I can only reach dynamically created routes after server restart which I want to avoid.<br>The problem is not solved with query params, because the dynamically added routes differ in logic, model properties, http methods/verbs and API endpoints. e.g.<br>GET/POST /api/{endpoint}<br>GET/POST /api/foo/{endpoint}<br>GET/PUT/DELETE /api/foo/bar/{endpoint}/:id<br><br>
  I think I basically need to either:<br>1) find a way to mount the dynamically created routes before the error handling - which I'm currently stuck at or<br>2) modify the route stack - which I have read is impractical, slow, bad practice and error prone<br>3) find an alternative solution<br><br>I hope someone can help me.<br>Thanks in advance<br><br><strong>EDIT</strong><br>Here is the code for the creation of new routes. The relevant endpoint is /api/databases/ in the POST method</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const Database = require('../models/database');
  const controller = require('./template/controller');
  const creation = require('../Creation');
  
  ...
  
  exports.createOne = (req, res, next) =&gt; {
    if (!creation.findFileInDirectory(`./backend/api/models/${req.body.name.singular}.js`) ||
        !creation.findFileInDirectory(`./backend/api/controllers/${req.body.name.singular}.js`) ||
        !creation.findFileInDirectory(`./backend/api/routes/${req.body.name.singular}.js`)) {
      controller.createOne(req, res, next, Database, {
        modelName: 'database',
      }, () =&gt; {
        //creation.createEndpoint(req.body.name, req.body.data, req.body.auth);
        creation.createEndpoint(req.body.name, req.body, req.body.auth);
      });
    } else {
      res.status(422).json({message: 'Endpoint exists already'});
    }
  }
  
  ...</code></pre>
  </div>
  </div>
  </p>
  <p>The controller in the snippet is just a modular controller file, which handles all of my CRUD Operations of all the endpoints of different models. Each route is split into models, controllers and routes to seperate and better maintain their logic.<br><br>In the POST method I first check whether the endpoint to be created already exists. If it does I respond with a 422 respond that the endpoint already exists. If it does not exist I create an entry mith my modular controller in the databases endpoint and create a model, controller &amp; route for the endpoint which should be created.<br><br>The creation logic is the following:</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const createEndpoint = (name, data, auth) =&gt; {
      createFile(`./backend/api/models/${name.singular}.js`, model.createModel(capitalize(name.singular), data), () =&gt; {
        createFile(`./backend/api/controllers/${name.singular}.js`, controller.createController({singular: capitalize(name.singular), plural: name.plural}, data.data), () =&gt; {
          createFile(`./backend/api/routes/${name.singular}.js`, route.createRoute({singular: capitalize(name.singular), plural: name.plural}, auth), () =&gt; {
            const app = require('../../app');
            mountEndpoints(name.singular, app);
          });
        });
      });
  };</code></pre>
  </div>
  </div>
  </p>
  <p>Here I basically pass along the data from the POST method to the model, controller &amp; route file which are created asynchronously. When all files are created I mount the endpoint route to the app. The logic to mount the route is:</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const mountEndpoints = (path, app) =&gt; {
    const module = require(`../routes/${path}`);
    app.use(`/api/${module.plural ? `${module.plural}` : `${path}s`}`, module);
  }</code></pre>
  </div>
  </div>
  </p>
  <p>A created route might look like the following:</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const express   = require('express');
  const router    = express.Router();
  const checkAuth = require('../middleware/check-auth');
  
  const ProductController = require('../controllers/product');
  
  router.route('/')
      .get(ProductController.getAll)
      .post(checkAuth, ProductController.createOne);
  
  router.route('/:id')
      .get(ProductController.getOne)
      .patch(checkAuth, ProductController.patchOne)
      .delete(checkAuth, ProductController.deleteOne);
  
  module.exports = router;
  module.exports.plural = 'products';</code></pre>
  </div>
  </div>
  </p>
  <p>checkAuth includes some logic for authorization/authentication.<br><br>The code does pretty much what I want it to do except that I don't know how to handle the positioning of the route before the error handling.</p>