I'm trying to create a reverse proxy with express and http-proxy-middleware@2.0.1 with some built-in validation. The hope is that in the onProxyReq function, I can perform a check, and if it fails, I'd return the error to the caller instead of continuing to proxy the request.
It seems that if I send a 404 with "Invalid" immediately, then it works as expected. If there is any delay while performing the validation operation (simulatied here with the setTimeout()) then it throws the error "Cannot set headers after they are send to the client". Is there a way I can get that onProxyReq to "wait" until my validation completes and I can decide whether or not I need to respond to client with error, or continue with proxy.
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
function onProxyReq(proxyReq, req, res) {
// Some validation
// ** This causes the error "Cannot set headers after they are sent to the client"
// setTimeout(()=>{
// res.status(404).send('Invalid')
// }, 500)
// ** This returns "Invalid" to the client as expected
return res.status(404).send('Invalid')
}
// proxy middleware options
const options = {
target: 'https://google.com',
changeOrigin: true,
logLevel: 'debug',
onProxyReq,
};
const testProxy = createProxyMiddleware(options);
const app = express();
app.use('/', testProxy);
app.listen(3000);