Core proxy middleware creation functionality providing comprehensive configuration options for HTTP proxy behavior.
Main factory function that creates HTTP proxy middleware instances with extensive configuration support.
/**
* Creates a proxy middleware instance with the specified options
* @param options - Configuration options for the proxy middleware
* @returns RequestHandler function that can be used with Express, Connect, etc.
*/
function createProxyMiddleware<
TReq = http.IncomingMessage,
TRes = http.ServerResponse,
TNext = NextFunction,
>(options: Options<TReq, TRes>): RequestHandler<TReq, TRes, TNext>;The function accepts comprehensive options that extend the underlying http-proxy ServerOptions with additional middleware-specific features.
Usage Examples:
import { createProxyMiddleware } from "http-proxy-middleware";
// Basic proxy to target server
const basicProxy = createProxyMiddleware({
target: "http://api.example.com",
changeOrigin: true,
});
// Proxy with path filtering and rewriting
const apiProxy = createProxyMiddleware({
target: "http://api.example.com",
changeOrigin: true,
pathFilter: "/api/**",
pathRewrite: {
"^/api": "", // Remove /api prefix when forwarding
},
});
// Advanced proxy with custom routing and event handling
const advancedProxy = createProxyMiddleware({
target: "http://api.example.com",
changeOrigin: true,
pathFilter: (pathname, req) => {
return pathname.startsWith("/api") && req.method === "GET";
},
router: async (req) => {
// Dynamic target selection based on request
if (req.headers.host?.includes("staging")) {
return "http://staging-api.example.com";
}
return "http://api.example.com";
},
on: {
error: (err, req, res, target) => {
console.error("Proxy error:", err.message);
},
proxyRes: (proxyRes, req, res) => {
console.log(`${req.method} ${req.url} -> ${proxyRes.statusCode}`);
},
},
});Essential options for basic proxy setup that are commonly used across different proxy configurations.
interface CoreProxyOptions {
/** Target server URL where requests will be forwarded */
target?: string | URL | httpProxy.ServerOptions['target'];
/** Change the origin of the host header to the target URL */
changeOrigin?: boolean;
/** Timeout for outgoing proxy requests in milliseconds */
timeout?: number;
/** Additional headers to add to proxied requests */
headers?: { [key: string]: string };
/** Authentication information for the target server */
auth?: string;
/** SSL/TLS configuration for HTTPS targets */
secure?: boolean;
/** Custom agent for HTTP requests */
agent?: http.Agent;
/** Custom agent for HTTPS requests */
httpsAgent?: https.Agent;
}Configuration options specifically for WebSocket proxying and upgrade handling.
interface WebSocketConfig {
/** Enable WebSocket proxying */
ws?: boolean;
/** Timeout for WebSocket connections */
wsTimeout?: number;
/** Custom WebSocket subprotocols */
wsSubprotocols?: string[];
}WebSocket Usage Examples:
// Basic WebSocket proxying
const wsProxy = createProxyMiddleware({
target: "ws://websocket.example.com",
ws: true,
changeOrigin: true,
});
// WebSocket with custom timeout and protocols
const customWsProxy = createProxyMiddleware({
target: "wss://secure-websocket.example.com",
ws: true,
wsTimeout: 30000,
wsSubprotocols: ["chat", "notification"],
secure: true,
});Configuration for secure HTTPS and WSS connections with custom certificate handling.
interface SSLConfig {
/** Verify SSL certificates (default: true) */
secure?: boolean;
/** Custom CA certificates */
ca?: string | Buffer | Array<string | Buffer>;
/** Client certificate */
cert?: string | Buffer;
/** Client private key */
key?: string | Buffer;
/** Passphrase for private key */
passphrase?: string;
}SSL Usage Examples:
// Disable SSL verification for development
const devProxy = createProxyMiddleware({
target: "https://self-signed.example.com",
secure: false,
changeOrigin: true,
});
// Custom SSL certificate configuration
const sslProxy = createProxyMiddleware({
target: "https://secure-api.example.com",
secure: true,
ca: fs.readFileSync("path/to/ca-cert.pem"),
cert: fs.readFileSync("path/to/client-cert.pem"),
key: fs.readFileSync("path/to/client-key.pem"),
});Configuration for handling request bodies, especially important for POST, PUT, and PATCH requests.
interface RequestBodyConfig {
/** Buffer request body before sending (useful with body parsers) */
buffer?: NodeJS.ReadableStream;
/** Custom request body modification function */
selfHandleResponse?: boolean;
/** Preserve original host header */
preserveHeaderKeyCase?: boolean;
/** Follow redirects from target server */
followRedirects?: boolean;
}Utility function for fixing request body issues when using body parsing middleware.
/**
* Fix request body issues when using with body parsing middleware like body-parser
* Call this function on the proxyReq event when the request body has been parsed
*/
function fixRequestBody<TReq extends BodyParserLikeRequest = BodyParserLikeRequest>(
proxyReq: http.ClientRequest,
req: TReq,
): void;
type BodyParserLikeRequest = http.IncomingMessage & { body?: any };Request Body Usage Examples:
import { createProxyMiddleware, fixRequestBody } from "http-proxy-middleware";
import bodyParser from "body-parser";
// Using with body parser middleware
app.use(bodyParser.json());
const proxyWithBodyFix = createProxyMiddleware({
target: "http://api.example.com",
changeOrigin: true,
on: {
proxyReq: fixRequestBody,
},
});
// Manual body handling
const manualBodyProxy = createProxyMiddleware({
target: "http://api.example.com",
selfHandleResponse: true,
on: {
proxyReq: (proxyReq, req, res) => {
// Custom request body handling
if (req.body) {
const bodyData = JSON.stringify(req.body);
proxyReq.setHeader('Content-Type', 'application/json');
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
proxyReq.write(bodyData);
}
},
},
});