Skip to content

Commit

Permalink
Merge branch 'master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
aremishevsky authored Dec 2, 2020
2 parents e4961b1 + f77121f commit dbca54f
Showing 1 changed file with 75 additions and 0 deletions.
75 changes: 75 additions & 0 deletions recipes/async-response.md
Original file line number Diff line number Diff line change
@@ -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_

0 comments on commit dbca54f

Please sign in to comment.