Skip to content

Commit c4e2f51

Browse files
committed
docs: update README.md
1 parent a6d97e1 commit c4e2f51

File tree

1 file changed

+46
-20
lines changed

1 file changed

+46
-20
lines changed

README.md

Lines changed: 46 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -31,32 +31,58 @@ This middleware is implemented using the [`http-proxy`](https://www.npmjs.com/pa
3131
- Priority is determined in the order entered in the array.
3232
- If the request URL matches the pattern `pathRewrite.patternStr` replace the URL string with the value `pathRewrite.replaceStr`.
3333

34+
### `onProxyInit` option
35+
- You can access the `http-proxy` instance using the `onProxyInit` option. See the example below.
36+
37+
```ts
38+
const handleProxyInit = (proxy: httpProxy) => {
39+
/**
40+
* Check the list of bindable events in the `http-proxy` specification.
41+
* @see https://www.npmjs.com/package/http-proxy#listening-for-proxy-events
42+
*/
43+
proxy.on('proxyReq', (proxyRes, req, res) => {
44+
...
45+
});
46+
proxy.on('proxyRes', (proxyRes, req, res) => {
47+
...
48+
});
49+
};
50+
51+
export default async (req: NextApiRequest, res: NextApiResponse)
52+
=> httpProxyMiddleware(req, res, {
53+
...
54+
target: 'http://example.com',
55+
onProxyInit: handleProxyInit,
56+
}
57+
);
58+
```
59+
3460
#### Example
3561

3662
- Refer to the following for how to use Nextjs API Middleware
3763

3864
- [Next.js API Middlewares Guide](https://nextjs.org/docs/api-routes/api-middlewares)
3965

40-
```typescript
41-
// pages/api/[...all].ts
42-
...
43-
export default (req: NextApiRequest, res: NextApiResponse) => (
44-
isDevelopment
45-
? httpProxyMiddleware(req, res, {
46-
// You can use the `http-proxy` option
47-
target: 'https://www.example.com',
48-
// In addition, you can use the `pathRewrite` option provided by `next-http-proxy-middleware`
49-
pathRewrite: [{
50-
patternStr: '^/api/new',
51-
replaceStr: '/v2'
52-
}, {
53-
patternStr: '^/api',
54-
replaceStr: ''
55-
}],
56-
})
57-
: res.status(404).send(null)
58-
);
59-
```
66+
```ts
67+
// pages/api/[...all].ts
68+
...
69+
export default (req: NextApiRequest, res: NextApiResponse) => (
70+
isDevelopment
71+
? httpProxyMiddleware(req, res, {
72+
// You can use the `http-proxy` option
73+
target: 'https://www.example.com',
74+
// In addition, you can use the `pathRewrite` option provided by `next-http-proxy-middleware`
75+
pathRewrite: [{
76+
patternStr: '^/api/new',
77+
replaceStr: '/v2'
78+
}, {
79+
patternStr: '^/api',
80+
replaceStr: ''
81+
}],
82+
})
83+
: res.status(404).send(null)
84+
);
85+
```
6086

6187
#### Using `multipart/form-data`
6288
* If you are using the `multipart/form-data`, refer to the Issues below

0 commit comments

Comments
 (0)