Examples to use http-proxy-middleware with WebSocket support.
- WebSocket -
ws:trueflag (automatic upgrade subscription) - WebSocket - Manual server upgrade subscription
- Multiple WebSocket targets
- WebSocket - Path Rewrite
ws: true requires an initial regular HTTP request, so HPM can subscribe to the server upgrade event internally.
💡 Use server.on('upgrade', proxy.upgrade) without the need of an initial HTTP request.
import { createProxyMiddleware } from 'http-proxy-middleware';
const socketProxy = createProxyMiddleware({
target: 'http://localhost:3000',
ws: true,
});Manually subscribe to server's upgrade event.
import { createProxyMiddleware } from 'http-proxy-middleware';
const socketProxy = createProxyMiddleware({
target: 'http://localhost:3000',
pathFilter: '/socket',
ws: true,
});
server.on('upgrade', socketProxy.upgrade); // <-- subscribe to http 'upgrade'Mount each websocket proxy with different target on its own route.
import express from 'express';
import { createProxyMiddleware } from 'http-proxy-middleware';
const app = express();
const wsProxyA = createProxyMiddleware({
target: 'http://localhost:4001',
pathFilter: '/ws-path-a',
ws: true,
});
const wsProxyB = createProxyMiddleware({
target: 'http://localhost:4002',
pathFilter: '/ws-path-b',
ws: true,
});
app.use('/ws-path-a', wsProxyA);
app.use('/ws-path-b', wsProxyB);This example will create a proxy middleware with websocket support and pathRewrite.
import { createProxyMiddleware } from 'http-proxy-middleware';
const options = {
target: 'http://localhost:3000',
ws: true,
pathFilter: '/socket',
pathRewrite: {
'^/socket': '',
},
};
const socketProxy = createProxyMiddleware(options);