From f77121f0c10715db127e7436ea88b0e2435f9fcb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=D0=B0=D0=B0=D1=80=D1=82=D0=B5=D0=BD=20-=20Maarten?= Date: Tue, 24 Nov 2020 21:49:33 +0100 Subject: [PATCH] docs(recipe): async onProxyRes response header (#485) * chore: show async response header * fix: linting * chore: show working example * chore: for before proxy you have two options sometimes we chain stuff with already existing middleware * chore: text * fix: show how to restart server in order to see the flow correctly Co-authored-by: Maarten van Oudenniel --- recipes/async-response.md | 75 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 recipes/async-response.md diff --git a/recipes/async-response.md b/recipes/async-response.md new file mode 100644 index 00000000..9526fc36 --- /dev/null +++ b/recipes/async-response.md @@ -0,0 +1,75 @@ +# Async proxied response + +Sometimes we need the ability to modify the response headers of the response of the proxied backend before sending it. For achieving it just make sure you have selfHandleResponse to true and add a pipe in the proxyRes: + +```javascript +const myProxy = createProxyMiddleware({ + target: 'http://www.example.com', + changeOrigin: true, + selfHandleResponse: true, + onProxyReq: (proxyReq, req, res) => { + // before + proxyReq.setHeader('mpth-1', 'da'); + }, + onProxyRes: async (proxyRes, req, res) => { + const da = await new Promise((resolve, reject) => { + setTimeout(() => { + resolve({ wei: 'wei' }); + }, 200); + }); + + // add your dynamic header + res.setHeader('mpth-2', da.wei); + + // now pipe the response + proxyRes.pipe(res); + }, +}); + +app.use('/api', myProxy); +``` + +There are also cases where you need to modify the request header async, we can achieve this by applying middleware in front of the proxy. Like: + +```javascript +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', + changeOrigin: true, + selfHandleResponse: true, + onProxyReq: (proxyReq, req, res) => { + // before + // get something async from entry middlware before the proxy kicks in + console.log('proxyReq:', req.locals.da); + + proxyReq.setHeader('mpth-1', req.locals.da); + }, + onProxyRes: async (proxyRes, req, res) => { + const da = await new Promise((resolve, reject) => { + setTimeout(() => { + resolve({ wei: 'wei' }); + }, 200); + }); + + // end: + res.setHeader('mpth-2', da.wei); + + proxyRes.pipe(res); + }, +}); + +app.use('/api', entryMiddleware, myProxy); +``` + +_working sample available at: [codesandbox.io/s/holy-resonance-yz552](https://codesandbox.io/s/holy-resonance-yz552?file=/src/index.js) Server Control Panel: restart server, see logging_