Skip to content

Commit

Permalink
docs(recipe): async onProxyRes response header (#485)
Browse files Browse the repository at this point in the history
* 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 <maarten.oudenniel.van@ahold.com>
  • Loading branch information
maapteh and Maarten van Oudenniel committed Nov 24, 2020
1 parent f212a04 commit f77121f
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 f77121f

Please sign in to comment.