Search code examples
node.jshttp-proxy-middleware

http-proxy-middleware: return custom error instead of proxying the request


The http-proxy-middleware Nodejs module provides a way of re-target request using a function in the option.router parameter. As described here:

router: function(req) {
    return 'http://localhost:8004';
}

I'll need to implement a process that check some aspect in the request (headers, URLs... all that information is at hand in the req object that function receives) and return a 404 error in some case. Something like this:

router: function(req) {
    if (checkRequest(req)) {
        return 'http://localhost:8004';
    }
    else {
        // Don't proxy and return a 404 to the client
    }
}

However, I don't know how to solve that // Don't proxy and return a 404 to the client. Looking to http-proxy-middleware is not so evident (or at least I haven't found the way...).

Any help/feedback on this is welcomed!


Solution

  • At the end I have solved throwing and expection and using the default Express error handler (I didn't mention in the question post, but the proxy lives in a Express-based application).

    Something like this:

    app.use('/proxy/:service/', proxy({
            ...
            router: function(req) {
                if (checkRequest(req)) {
                    // Happy path
                    ...
                    return target;
                }
                else {
                    throw 'awfull error';
                }
            }
    }));
    
    ...
    
    // Handler for global and uncaugth errors
    app.use(function (err, req, res, next) {
        if (err === 'awful error') {
            res.status(404).send();
        }
        else {
            res.status(500).send();
        }
        next(err);
    });