Since the proxyReq event handler is synchronous, you cannot directly await inside it to modify request headers. To achieve asynchronous request header modification, apply an asynchronous middleware function before the proxy middleware in your application stack. This middleware can perform async operations and attach data to the req object (e.g., req.locals), which can then be accessed synchronously within the proxyReq handler.
const entryMiddleware = async (req, res, next) => {
const foo = await new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ da: 'da' });
}, 200);
});
req.locals = {
da: foo.da,
};
next();
};
const myProxy = createProxyMiddleware({
target: 'http://www.example.com/api',
changeOrigin: true,
selfHandleResponse: true,
on: {
proxyReq: (proxyReq, req, res) => {
// get something async from entry middleware before the proxy kicks in
console.log('proxyReq:', req.locals.da);
proxyReq.setHeader('mpth-1', req.locals.da);
},
proxyRes: async (proxyRes, req, res) => {
const da = await new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ wei: 'wei' });
}, 200);
});
res.setHeader('mpth-2', da.wei);
proxyRes.pipe(res);
},
},
});
app.use('/api', entryMiddleware, myProxy);