@@ -39,28 +39,62 @@ bun install @squarecloud/http-proxy
3939
4040Create proxy:
4141
42- ``` ts
43- import { createServer } from " node:http" ;
44-
45- import { createProxyServer } from " @squarecloud/http-proxy" ;
42+ ``` js
43+ const { createServer } = require (" node:http" );
44+ const { createProxyServer } = require (" @squarecloud/http-proxy" );
4645
4746const proxy = createProxyServer ({});
4847const target = " http://example.com" ; /* address of your proxy server here */
4948
5049const server = createServer (async (req , res ) => {
51- try {
52- await proxy .web (req , res , { target });
53- } catch (error ) {
54- console .error (error );
55- res .statusCode = 500 ;
56- res .end (" Proxy error: " + error .toString ());
57- }
50+ try {
51+ await proxy .web (req, res, { target });
52+ } catch (error) {
53+ console .error (error);
54+ res .statusCode = 500 ;
55+ res .end (" Proxy error: " + error .toString ());
56+ }
5857});
5958
6059server .listen (80 , () => console .log (" Proxy is listening on http://localhost" ));
6160```
6261
63- Checkout [ http-party/node-http-proxy] ( https://github.com/http-party/node-http-proxy ) for more options and examples.
62+ Example with WebSocket:
63+
64+ ``` js
65+ const { createServer } = require (" node:http" );
66+ const { createProxyServer } = require (" @squarecloud/http-proxy" );
67+
68+ const proxy = createProxyServer ({ ws: true });
69+ const target = " ws://example.com" ; /* address of your proxy server here */
70+
71+ const server = createServer (async (req , res ) => { /* ... */ });
72+
73+ server .on (" upgrade" , async (req , socket , head ) => {
74+ try {
75+ // use proxy.ws() instead of proxy.web() for proxying WebSocket requests.
76+ await proxy .ws (req, socket, head, { target });
77+ } catch (error) {
78+ console .error (error);
79+ socket .end ();
80+ }
81+ });
82+
83+ server .listen (80 , () => console .log (" Proxy is listening on http://localhost" ));
84+ ```
85+
86+ Some options:
87+
88+ ``` js
89+ // Options most used in the proxy configuration:
90+ // * ws : <true/false, if you want to proxy websockets>
91+ // * xfwd : <true/false, adds X-Forward headers>
92+ // * secure : <true/false, verify SSL certificate>
93+ // * prependPath: <true/false, Default: true - specify whether you want to prepend the target"s path to the proxy path>
94+ // * ignorePath: <true/false, Default: false - specify whether you want to ignore the proxy path of the incoming request>
95+ ```
96+
97+ Checkout [ http-party/node-http-proxy] ( https://github.com/http-party/node-http-proxy#options ) for more options and examples.
6498
6599## Development
66100
0 commit comments