Skip to content

Commit f77121f

Browse files
maaptehMaarten van Oudenniel
and
Maarten van Oudenniel
authored
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 <[email protected]>
1 parent f212a04 commit f77121f

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

recipes/async-response.md

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# Async proxied response
2+
3+
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:
4+
5+
```javascript
6+
const myProxy = createProxyMiddleware({
7+
target: 'http://www.example.com',
8+
changeOrigin: true,
9+
selfHandleResponse: true,
10+
onProxyReq: (proxyReq, req, res) => {
11+
// before
12+
proxyReq.setHeader('mpth-1', 'da');
13+
},
14+
onProxyRes: async (proxyRes, req, res) => {
15+
const da = await new Promise((resolve, reject) => {
16+
setTimeout(() => {
17+
resolve({ wei: 'wei' });
18+
}, 200);
19+
});
20+
21+
// add your dynamic header
22+
res.setHeader('mpth-2', da.wei);
23+
24+
// now pipe the response
25+
proxyRes.pipe(res);
26+
},
27+
});
28+
29+
app.use('/api', myProxy);
30+
```
31+
32+
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:
33+
34+
```javascript
35+
const entryMiddleware = async (req, res, next) => {
36+
const foo = await new Promise((resolve, reject) => {
37+
setTimeout(() => {
38+
resolve({ da: 'da' });
39+
}, 200);
40+
});
41+
req.locals = {
42+
da: foo.da,
43+
};
44+
next();
45+
};
46+
47+
const myProxy = createProxyMiddleware({
48+
target: 'http://www.example.com',
49+
changeOrigin: true,
50+
selfHandleResponse: true,
51+
onProxyReq: (proxyReq, req, res) => {
52+
// before
53+
// get something async from entry middlware before the proxy kicks in
54+
console.log('proxyReq:', req.locals.da);
55+
56+
proxyReq.setHeader('mpth-1', req.locals.da);
57+
},
58+
onProxyRes: async (proxyRes, req, res) => {
59+
const da = await new Promise((resolve, reject) => {
60+
setTimeout(() => {
61+
resolve({ wei: 'wei' });
62+
}, 200);
63+
});
64+
65+
// end:
66+
res.setHeader('mpth-2', da.wei);
67+
68+
proxyRes.pipe(res);
69+
},
70+
});
71+
72+
app.use('/api', entryMiddleware, myProxy);
73+
```
74+
75+
_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 commit comments

Comments
 (0)