Search code examples
javascriptnode.jsexpressroutesmiddleware

How to clear middleware loading to make dynamic route loading?


I don't know if it's possible, but I need to loading dinamically route files in middleware, according to a conditional.

Here we have the code that do well job in the first request, but seems that in next request, he enters inside right place of conditional but not use right file, seems that he uses cache file or something of previous request...

let routesApp = require('./routes-app');
let routesWeb = require('./routes-web');

app.use((req, res, next) => {
    const regex = new RegExp(pattern, 'i')
    if (regex.test(req.headers['agent-type'])) {
        app.use('/', routesWeb)
    } else {
        app.use('/', routesApp)
    }
    return next()
})

How do I make this works?


Solution

  • When you call app.use the middleware passed to it gets registered for that path and subsequent requests will be handled by that .

    One way to handle what you are doing is define a middleware which conditionally delegates to your web or mobile middleware as needed.

    Sample Code:

    let routesApp = require('./routes-app');
    let routesWeb = require('./routes-web');
    
    app.use('/', (req, res, next) => {
        const regex = new RegExp(pattern, 'i')
        if (regex.test(req.headers['agent-type'])) {
            routesWeb(req, res, next);
        } else {
            routesApp(req, res, next);
        }
    })