[Fixed] Dynamically changing routes in Express


I have an express server. This is my index.js

let some_parameter = some_value;
const configuredHandler = new Handler(some_parameter);

const server = express();

    .get("*", configuredHandler.handleRequest)
    .post("*", configuredHandler.handleRequest)
    .put("*", configuredHandler.handleRequest)
    .delete("*", configuredHandler.handleRequest);

I am trying to update the routes if some_parameter to the Handler changes. So it should create a new instance of configuredHandler and the routes should automatically pick the new handler.
Ideally I want to be able to change some_parameter anywhere else in the code.
I am not sure how to structure it for this.
Please help.


What you could do is use something similar to a factory. That factory would create a new middleware every time some_parameter changes and save that middleware for future reference.

Whenever one of your routes is called, express would then refer to the current handler in your factory.

I wrote a simple example:

const express = require('express');

class HandlerFactory {

  static currentHandler = (req, res) => res.send('Hello');

  static setValue(value) {
    this.currentHandler = (req, res) => res.send(value);


const app = express();
app.post('/change-value', (req, res) => {
app.use('/handler', (req, res) => HandlerFactory.currentHandler(req, res));


Just run the app, then test its functionality:

$ curl http://localhost:3000/handler
$ curl -X POST http://localhost:3000/change-value?value=SecondMessage
$ curl http://localhost:3000/handler

Leave a Reply

(*) Required, Your email will not be published