### Start Next.js Development Server Source: https://github.com/chimurai/http-proxy-middleware/blob/master/examples/next-app/PROXY.md Command to initiate the local development server from the examples directory. ```sh npm run dev ``` -------------------------------- ### Install dependencies Source: https://github.com/chimurai/http-proxy-middleware/blob/master/examples/README.md Commands to clone the repository and install necessary dependencies for running examples. ```shell # git clone https://github.com/chimurai/http-proxy-middleware.git yarn install:all yarn build ``` -------------------------------- ### Run server examples Source: https://github.com/chimurai/http-proxy-middleware/blob/master/examples/README.md Commands to execute specific server implementation examples from the root directory. ```shell node examples/browser-sync ``` ```shell node examples/connect ``` ```shell node examples/express ``` ```shell node examples/websocket ``` -------------------------------- ### Install Dependencies and Run Tests Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Commands to install project dependencies, run linting, build the project, execute unit tests, check code coverage, and perform spell checks. ```bash # install dependencies $ yarn # linting $ yarn lint $ yarn lint:fix # building (compile typescript to js) $ yarn build # unit tests $ yarn test # code coverage $ yarn coverage # check spelling mistakes $ yarn spellcheck ``` -------------------------------- ### Install http-proxy-middleware Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Install the http-proxy-middleware package as a development dependency using npm. ```shell npm install --save-dev http-proxy-middleware ``` -------------------------------- ### Setup Proxy with Express Server Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md Integrate proxy middleware into an Express application. This example shows how to proxy requests to '/api' to a target server. Ensure express and http-proxy-middleware are imported. ```javascript import express from 'express'; import { createProxyMiddleware } from 'http-proxy-middleware'; const apiProxy = createProxyMiddleware({ target: 'http://www.example.org/api', changeOrigin: true, // for vhosted sites }); const app = express(); app.use('/api', apiProxy); app.listen(3000); ``` -------------------------------- ### Run Development Server Source: https://github.com/chimurai/http-proxy-middleware/blob/master/examples/next-app/README.md Commands to start the development server using different package managers. Ensure you are in the project's root directory. ```bash npm run dev ``` ```bash yarn dev ``` ```bash pnpm dev ``` ```bash bun dev ``` -------------------------------- ### Connect Server with API Proxy Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md Set up a Connect server to proxy API requests to a target server. Ensure 'connect' and 'http-proxy-middleware' are installed. ```javascript import * as http from 'node:http'; import connect from 'connect'; import { createProxyMiddleware } from 'http-proxy-middleware'; const apiProxy = createProxyMiddleware({ target: 'http://www.example.org/api', changeOrigin: true, // for vhosted sites }); const app = connect(); app.use('/api', apiProxy); http.createServer(app).listen(3000); ``` -------------------------------- ### Setup Proxy with Node.js http.createServer Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md Use this snippet to configure proxy middleware for a vanilla Node.js http server. Ensure http and http-proxy-middleware are imported. ```javascript import * as http from 'node:http'; import { createProxyMiddleware } from 'http-proxy-middleware'; /** * Configure proxy middleware */ const apiProxy = createProxyMiddleware({ target: 'http://www.example.com', changeOrigin: true, // for vhosted sites, changes host header to match to target's host }); const server = http.createServer(apiProxy); server.listen(3000); ``` -------------------------------- ### Add Base Path Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathRewrite.md Add a base path to the request URL. This example prepends '/extra/' to all requests, so '/api/lorum/ipsum' becomes '/extra/api/lorum/ipsum'. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; const options = { target: 'http://localhost:3000', pathRewrite: { '^/': '/extra/', // add base path }, }; const apiProxy = createProxyMiddleware(options); // `/api/lorum/ipsum` -> `http://localhost:3000/extra/api/lorum/ipsum` ``` -------------------------------- ### Create Custom Plugin with definePlugin Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Use definePlugin to create your own http-proxy-middleware plugins. This example shows basic plugin definition and usage with createProxyMiddleware. ```typescript import { createProxyMiddleware, definePlugin } from 'http-proxy-middleware'; const myPlugin = definePlugin((proxyServer, options) => { // plugin implementation }); // use configure and use plugin createProxyMiddleware({ target: `http://example.org`, plugins: [myPlugin], }); ``` -------------------------------- ### Example Debug Output from http-proxy-middleware Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Illustrates typical log messages when debug logging is enabled for http-proxy-middleware. These messages show proxy creation and request forwarding. ```shell $ http-proxy-middleware proxy created +0ms $ http-proxy-middleware proxying request to target: 'http://www.example.org' +359ms ``` -------------------------------- ### Basic WebSocket Proxy Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Use this snippet for a verbose API setup for WebSocket proxying. ```javascript // verbose api createProxyMiddleware({ pathFilter: '/', target: 'http://echo.websocket.org', ws: true }); ``` -------------------------------- ### Match single path with pathFilter Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathFilter.md Matches requests starting with a specific path prefix. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; const apiProxy = createProxyMiddleware({ target: 'http://localhost:3000', pathFilter: '/api', }); // `/api/foo/bar` -> `http://localhost:3000/api/foo/bar` ``` -------------------------------- ### Path Rewrite: Add Base Path Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Add a base path to the target URL by rewriting the root path. This example adds '/basepath/' to all paths. ```javascript pathRewrite: {'^/' : '/basepath/'} ``` -------------------------------- ### Gulp Webserver with API Proxy Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md Set up a Gulp task using gulp-webserver to serve static files and proxy API requests with http-proxy-middleware. Make sure to install http-proxy-middleware and gulp-webserver. ```javascript import gulp from 'gulp'; import webserver from 'gulp-webserver'; import { createProxyMiddleware } from 'http-proxy-middleware'; gulp.task('webserver', function () { const apiProxy = createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true, // for vhosted sites pathFilter: '/api', }); gulp.src('app').pipe( webserver({ livereload: true, directoryListing: true, open: true, middleware: [apiProxy], }), ); }); gulp.task('default', ['webserver']); ``` -------------------------------- ### Rewrite Paths Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathRewrite.md Use a regular expression to rewrite a specific path. The example shows how to change '/api/old-path' to '/api/new-path'. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; const options = { target: 'http://localhost:3000', pathRewrite: { '^/api/old-path': '/api/new-path', // rewrite path }, }; const apiProxy = createProxyMiddleware(options); // `/api/old-path/foo/bar` -> `http://localhost:3000/api/new-path/foo/bar` ``` -------------------------------- ### Plugins: Simple Request Logger Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Add a custom plugin to log proxy requests. This example uses the 'proxyReq' event to log the method and URL of outgoing proxy requests. ```javascript const simpleRequestLogger = (proxyServer, options) => { proxyServer.on('proxyReq', (proxyReq, req, res) => { console.log(`[HPM] [${req.method}] ${req.url}`); // outputs: [HPM] GET /users }); }, const config = { target: `http://example.org`, changeOrigin: true, plugins: [simpleRequestLogger], }; ``` -------------------------------- ### Path Rewrite: Basic Rewrite Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Rewrite the target URL path using a regular expression to match and replace parts of the path. This example rewrites '/old/api' to '/new/api'. ```javascript pathRewrite: {'^/old/api' : '/new/api'} ``` -------------------------------- ### Grunt BrowserSync with API Proxy Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md Configure Grunt BrowserSync to use http-proxy-middleware for proxying API requests. Ensure http-proxy-middleware is installed as a dev dependency. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; const apiProxy = createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true, // for vhosted sites pathFilter: '/api', }); grunt.initConfig({ // BrowserSync Task browserSync: { default_options: { options: { files: ['css/*.css', '*.html'], port: 9000, server: { baseDir: ['app'], middleware: apiProxy, }, }, }, }, }); ``` -------------------------------- ### Proxy API Requests with Browser-Sync Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md Use this snippet to proxy API requests to a different origin when using Browser-Sync for development. Ensure BrowserSync is installed. ```javascript import BrowserSync from 'browser-sync'; import { createProxyMiddleware } from 'http-proxy-middleware'; const browserSync = BrowserSync.create(); const apiProxy = createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true, // for vhosted sites pathFilter: '/api', }); browserSync.init({ server: { baseDir: './', port: 3000, middleware: [apiProxy], }, startPath: '/api', }); ``` -------------------------------- ### Remove Base Path Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathRewrite.md Remove a base path from the request URL. This example removes '/api/' so that requests to '/api/lorum/ipsum' are proxied to '/lorum/ipsum'. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; const options = { target: 'http://localhost:3000', pathRewrite: { '^/api/': '/', // remove base path }, }; const apiProxy = createProxyMiddleware(options); // `/api/lorum/ipsum` -> `http://localhost:3000/lorum/ipsum` ``` -------------------------------- ### Path Rewrite: Remove Path Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Remove a specific path prefix from the target URL by rewriting it to an empty string. This example removes '/remove/api'. ```javascript pathRewrite: {'^/remove/api' : ''} ``` -------------------------------- ### Modify POST Body Data in http-proxy-middleware Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/modify-post.md Use the 'onProxyReq' event handler to manipulate POST request bodies. This example shows how to create a new POST body with modified parameters and update the request headers accordingly. Ensure 'body-parser' is used in the main app to parse the initial request body. ```javascript 'use strict'; import express from 'express'; import { createProxyMiddleware } from 'http-proxy-middleware'; const router = express.Router(); const proxy_options = { target: 'http://localhost:8080', pathRewrite: { '^/docs': '/java/rep/server1', // Host path & target path conversion }, pathFilter: function (path, req) { return path.match('^/docs') && (req.method === 'GET' || req.method === 'POST'); }, on: { error(err, req, res) { res.writeHead(500, { 'Content-Type': 'text/plain', }); res.end('Something went wrong. And we are reporting a custom error message.' + err); }, proxyReq(proxyReq, req, res) { if (req.method == 'POST' && req.body) { // Add req.body logic here if needed.... // .... // Remove body-parser body object from the request if (req.body) delete req.body; // Make any needed POST parameter changes let body = new Object(); body.filename = 'reports/statistics/summary_2016.pdf'; body.routeId = 's003b012d002'; body.authId = 'bac02c1d-258a-4177-9da6-862580154960'; // URI encode JSON object body = Object.keys(body) .map(function (key) { return encodeURIComponent(key) + '=' + encodeURIComponent(body[key]); }) .join('&'); // Update header proxyReq.setHeader('content-type', 'application/x-www-form-urlencoded'); proxyReq.setHeader('content-length', body.length); // Write out body changes to the proxyReq stream proxyReq.write(body); proxyReq.end(); } }, }, }; // Proxy configuration const proxy = createProxyMiddleware(proxy_options); /* GET home page. */ router.get('/', function (req, res, next) { res.render('index', { title: 'Node.js Express Proxy Test' }); }); router.all('/docs', proxy); module.exports = router; ``` -------------------------------- ### Basic Proxy Middleware Configuration Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Create a proxy middleware instance with target host and changeOrigin options. This middleware can then be used in a server. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; const apiProxy = createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true, }); // 'apiProxy' is now ready to be used as middleware in a server. ``` -------------------------------- ### Initialize Proxy Middleware Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/basic.md Creates a basic proxy middleware instance with a target URL and origin modification enabled. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; const apiProxy = createProxyMiddleware({ target: 'http://localhost:3000', changeOrigin: true, }); ``` -------------------------------- ### Configure pino logger Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/logger.md Integrate the pino logger for high-performance logging. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; import pino from 'pino'; const logger = pino(); const proxy = createProxyMiddleware({ target: 'http://localhost:3000', logger, }); ``` -------------------------------- ### Configure Middleware Routes Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/basic.md Demonstrates different ways to integrate the proxy middleware into an Express-like application using path filtering. ```javascript app.use('/api', createProxyMiddleware({ target: 'http://localhost:3000/api', changeOrigin: true })); ``` ```javascript app.use( createProxyMiddleware({ target: 'http://localhost:3000', changeOrigin: true, pathFilter: '/api', }), ); ``` -------------------------------- ### Router: Host and Path Matching Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Configure routing rules to re-target requests based on host and path. The order of rules matters, and the first match is used. ```javascript router: { 'integration.localhost:3000' : 'http://127.0.0.1:8001', // host only 'staging.localhost:3000' : 'http://127.0.0.1:8002', // host only 'localhost:3000/api' : 'http://127.0.0.1:8003', // host + path '/rest' : 'http://127.0.0.1:8004' // path only } ``` -------------------------------- ### Configure Logger with Console Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Configure http-proxy-middleware to use the console object for logging. Ensure your logger supports 'info', 'warn', and 'error' methods. ```javascript createProxyMiddleware({ logger: console, }); ``` -------------------------------- ### Configure winston logger Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/logger.md Integrate winston for advanced logging capabilities with support for interpolation. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; import * as winston from 'winston'; const { format, transports } = winston; // Enable interpolation in log messages // https://github.com/winstonjs/winston#string-interpolation const logger = winston.createLogger({ format: format.combine(format.splat(), format.simple()), transports: [new transports.Console()], }); const proxy = createProxyMiddleware({ target: 'http://localhost:3000', logger, }); ``` -------------------------------- ### Test Proxy with Curl Source: https://github.com/chimurai/http-proxy-middleware/blob/master/examples/next-app/PROXY.md Command-line utility to verify the proxy response from the local API route. ```bash curl http://localhost:3000/api/users ``` -------------------------------- ### Subscribe to httpxy Events Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Configure event handlers for proxy events like proxyReq, proxyRes, and error using the 'on' option in createProxyMiddleware. ```javascript createProxyMiddleware({ target: 'http://www.example.org', on: { proxyReq: (proxyReq, req, res) => { /* handle proxyReq */ }, proxyRes: (proxyRes, req, res) => { /* handle proxyRes */ }, error: (err, req, res) => { /* handle error */ }, }, }); ``` -------------------------------- ### Configure grunt-contrib-connect with http-proxy-middleware as an Array Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md Integrate http-proxy-middleware into grunt-contrib-connect by providing the proxy middleware directly in the 'middleware' array. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; const apiProxy = createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true, // for vhosted sites pathFilter: '/api', }); grunt.initConfig({ connect: { server: { options: { middleware: [apiProxy], }, }, }, }); ``` -------------------------------- ### Create Virtual Host Proxy Middleware Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/virtual-hosts.md Use this snippet to create a proxy middleware that forwards requests to a target server, modifying the Host header when 'changeOrigin' is true. This is useful for virtual hosting. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; const options = { target: 'http://localhost:3000', changeOrigin: true, }; const apiProxy = createProxyMiddleware(options); ``` -------------------------------- ### Configure gulp-connect with http-proxy-middleware Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md Set up http-proxy-middleware within the middleware function for gulp-connect to proxy API requests. ```javascript import gulp from 'gulp'; import connect from 'gulp-connect'; import { createProxyMiddleware } from 'http-proxy-middleware'; gulp.task('connect', function () { connect.server({ root: ['./app'], middleware: function (connect, opt) { const apiProxy = createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true, // for vhosted sites pathFilter: '/api', }); return [apiProxy]; }, }); }); gulp.task('default', ['connect']); ``` -------------------------------- ### Proxy Middleware with Fastify Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md Integrate createProxyMiddleware with a Fastify application using the @fastify/express plugin. This allows proxying requests to a specified target server. ```javascript import fastifyExpress from '@fastify/express'; import fastifyFactory from 'fastify'; import { createProxyMiddleware } from 'http-proxy-middleware'; const fastify = fastifyFactory({ logger: true }); (async () => { await fastify.register(fastifyExpress); const proxy = createProxyMiddleware({ target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, }); fastify.use(proxy); fastify.listen({ port: 3000 }, (err, address) => { if (err) throw err; fastify.log.info(`server listening on ${address}`); }); })(); // curl http://localhost:3000/users ``` -------------------------------- ### Enable Debug Logging for http-proxy-middleware Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Configure the DEBUG environment variable to enable detailed logging for http-proxy-middleware. This is useful for troubleshooting proxy behavior. ```shell DEBUG=http-proxy-middleware* node server.js ``` -------------------------------- ### Configure bunyan logger Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/logger.md Integrate bunyan for structured JSON logging. ```javascript import bunyan from 'bunyan'; import { createProxyMiddleware } from 'http-proxy-middleware'; const logger = bunyan.createLogger({ name: 'my-app', }); const proxy = createProxyMiddleware({ target: 'http://localhost:3000', logger, }); ``` -------------------------------- ### WebSocket - Manual Server Upgrade Subscription Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/websocket.md Manually subscribe to the server's upgrade event using `server.on('upgrade', proxy.upgrade)`. This method is useful when an initial HTTP request is not feasible. ```javascript 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' ``` -------------------------------- ### Configure console logger Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/logger.md Use the built-in console object for logging proxy activity. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; const proxy = createProxyMiddleware({ target: 'http://localhost:3000', logger: console, }); ``` -------------------------------- ### Create Proxy Middleware with Corporate Proxy Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/corporate-proxy.md Use this snippet to create a proxy middleware that connects through a corporate proxy. Ensure the HTTPS_PROXY or HTTP_PROXY environment variables are set. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; import { HttpsProxyAgent } from 'https-proxy-agent'; // corporate proxy to connect to const proxyServer = process.env.HTTPS_PROXY || process.env.HTTP_PROXY; const options = { target: 'http://localhost:3000', agent: new HttpsProxyAgent(proxyServer), }; const apiProxy = createProxyMiddleware(options); ``` -------------------------------- ### Update Context Matching from v2 to v3 Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/context-matching.md In v2, context matching was done by passing a string as the first argument. In v3, this has been moved to the 'pathFilter' option. Ensure your proxy configurations are updated accordingly. ```javascript // v2 createProxyMiddleware('/api', { target: 'http://localhost:3000', }); // v3 createProxyMiddleware({ target: 'http://localhost:3000', pathFilter: '/api', }); ``` -------------------------------- ### Log Request and Response Details Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/response-interceptor.md Utilize `responseInterceptor` to log details about the incoming request and the proxied request, as well as the complete response body. Set `selfHandleResponse: true` for proper functioning. ```javascript const proxy = createProxyMiddleware({ target: 'http://www.example.com', changeOrigin: true, // for vhosted sites selfHandleResponse: true, // res.end() will be called internally by responseInterceptor() on: { proxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => { // log original request and proxied request info const exchange = `[DEBUG] ${req.method} ${req.path} -> ${proxyRes.req.protocol}//${proxyRes.req.host}${proxyRes.req.path} [${proxyRes.statusCode}]`; console.log(exchange); // [DEBUG] GET / -> http://www.example.com [200] // log complete response const response = responseBuffer.toString('utf8'); console.log(response); // log response body return responseBuffer; }), }, }); ``` -------------------------------- ### Proxy API Requests with lite-server Configuration Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md Configure lite-server to proxy API requests using a middleware configuration file. This is useful for development environments. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; const apiProxy = createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true, // for vhosted sites pathFilter: '/api', }); export default { server: { // Start from key `10` in order to NOT overwrite the default 2 middleware provided // by `lite-server` or any future ones that might be added. // Reference: https://github.com/johnpapa/lite-server/blob/master/lib/config-defaults.js#L16 middleware: { 10: apiProxy, }, }, }; ``` -------------------------------- ### Configure grunt-contrib-connect with http-proxy-middleware as a Function Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md Use a function to define the middleware for grunt-contrib-connect, allowing for dynamic injection of http-proxy-middleware. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; const apiProxy = createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true, // for vhosted sites pathFilter: '/api', }); grunt.initConfig({ connect: { server: { options: { middleware: function (connect, options, middlewares) { // inject a custom middleware into the array of default middlewares middlewares.unshift(apiProxy); return middlewares; }, }, }, }, }); ``` -------------------------------- ### Path Rewrite: Custom Function with Promise Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Implement asynchronous path rewriting using a function that returns a Promise. This allows for I/O operations before determining the final path. ```javascript pathRewrite: async function (path, req, res, options) { const should_add_something = await httpRequestToDecideSomething(path); if (should_add_something) path += "something"; return path; } ``` -------------------------------- ### Handle WebSocket Open Event with onOpen Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md The onOpen event is triggered when a WebSocket connection to the target is established. Use it to listen for messages from the target. ```javascript function onOpen(proxySocket) { // listen for messages coming FROM the target here proxySocket.on('data', hybridParseAndLogMessage); } ``` -------------------------------- ### Proxy Middleware with Hono Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md Use createHonoProxyMiddleware to integrate http-proxy-middleware with a Hono application. This is useful for routing specific paths to a target server. ```javascript import { serve } from '@hono/node-server'; import { Hono } from 'hono'; import { createHonoProxyMiddleware } from 'http-proxy-middleware/hono'; const app = new Hono(); app.use( '/users', createHonoProxyMiddleware({ target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, // for vhosted sites, changes host header to match to target's host logger: console, }), ); const server = serve(app); // curl http://localhost:3000/users ``` -------------------------------- ### Multiple WebSocket Targets with Different Routes Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/websocket.md Mount multiple WebSocket proxies, each with a different target and path filter, on their own distinct routes within an Express application. ```javascript 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); ``` -------------------------------- ### Configure log4js logger Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/logger.md Integrate log4js and set the logging level to debug. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; import log4js from 'log4js'; const logger = log4js.getLogger(); logger.level = 'debug'; const proxy = createProxyMiddleware({ target: 'http://localhost:3000', logger, }); ``` -------------------------------- ### WebSocket - Automatic Upgrade Subscription Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/websocket.md Use the `ws: true` flag for automatic WebSocket upgrade subscription. This requires an initial regular HTTP request for the proxy to subscribe to the server upgrade event internally. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; const socketProxy = createProxyMiddleware({ target: 'http://localhost:3000', ws: true, }); ``` -------------------------------- ### Match paths with wildcards Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathFilter.md Uses glob patterns to match complex path structures. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; const apiProxy = createProxyMiddleware({ target: 'http://localhost:3000', pathFilter: '/api/**/*.json', }); ``` -------------------------------- ### Implement Request and Response Delay Middleware Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/delay.md Use this middleware before your proxy handler to delay requests by a specified time and increase the response completion time. It targets specific URLs and applies delays using setTimeout. ```javascript const myProxy = createProxyMiddleware({ target: 'http://www.example.com', changeOrigin: true, }); const proxyDelay = function (req, res, next) { if (req.originalUrl === '/api/get-me-something') { // Delay request by 2 seconds setTimeout(next, 2000); // Delay response completion by 5 seconds const endOriginal = res.end; res.end = function (...args) { setTimeout(function () { endOriginal.apply(res, args); }, 5000); }; } else { next(); } }; app.use('/api', proxyDelay, myProxy); ``` -------------------------------- ### Test Proxy URL Source: https://github.com/chimurai/http-proxy-middleware/blob/master/examples/next-app/PROXY.md The local endpoint to verify the proxy configuration in a browser. ```text http://localhost:3000/api/users ``` -------------------------------- ### Basic HTTPS Server Proxy Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/https.md Use this snippet to proxy requests to a standard HTTPS server. Ensure 'changeOrigin' is set to true for correct host header handling. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; const apiProxy = createProxyMiddleware({ target: 'https://example.org', changeOrigin: true, }); ``` -------------------------------- ### Match multiple paths with pathFilter Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathFilter.md Accepts an array of strings to match multiple path prefixes. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; const apiProxy = createProxyMiddleware({ target: 'http://localhost:3000', pathFilter: ['/api', '/rest'], }); // `/api/foo/bar` -> `http://localhost:3000/api/foo/bar` // `/rest/lorum/ipsum` -> `http://localhost:3000/rest/lorum/ipsum` ``` -------------------------------- ### Match multiple paths with wildcards Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathFilter.md Combines multiple glob patterns in an array. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; const apiProxy = createProxyMiddleware({ target: 'http://localhost:3000', pathFilter: ['/api/**/*.json', '/rest/**'], }); ``` -------------------------------- ### Proxy Table for Routing Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/router.md Configure routing using a proxy table object. This allows mapping hostnames and paths to specific target URLs. ```javascript import express from 'express'; import { createProxyMiddleware } from 'http-proxy-middleware'; const proxyTable = { 'integration.localhost:3000': 'http://localhost:8001', // host only 'staging.localhost:3000': 'http://localhost:8002', // host only 'localhost:3000/api': 'http://localhost:8003', // host + path '/rest': 'http://localhost:8004', // path only }; const options = { target: 'http://localhost:8000', router: proxyTable, }; const myProxy = createProxyMiddleware(options); const app = express(); app.use(myProxy); // add the proxy to express app.listen(3000); ``` -------------------------------- ### External WebSocket Upgrade Handling Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Proxy WebSockets without an initial HTTP request by subscribing to the server's HTTP 'upgrade' event manually. This is useful when the middleware is attached to multiple servers. ```javascript const wsProxy = createProxyMiddleware({ target: 'ws://echo.websocket.org', changeOrigin: true }); const app = express(); app.use(wsProxy); const server = app.listen(3000); server.on('upgrade', wsProxy.upgrade); // <-- subscribe to http 'upgrade' ``` -------------------------------- ### Router: Custom Function (Target Object) Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Configure a custom router function that returns a target object with protocol, host, and port. This allows for more detailed target specification. ```javascript router: function(req, res, options) { return { protocol: 'https:', // The : is required host: '127.0.0.1', port: 8004 }; } ``` -------------------------------- ### Proxy API Requests with Polka Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md Integrate http-proxy-middleware with the Polka framework to proxy API requests. Polka is a lightweight web server. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; import polka from 'polka'; const app = polka(); app.use( createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true, }), ); app.listen(3000); ``` -------------------------------- ### Match paths with exclusion globs Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathFilter.md Uses the '!' prefix to exclude specific patterns from being proxied. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; const apiProxy = createProxyMiddleware({ target: 'http://localhost:3000', pathFilter: ['foo/*.js', '!bar.js'], }); ``` -------------------------------- ### Proxy Middleware with pathFilter Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Configure proxy middleware to only proxy requests matching a specific path using the pathFilter option within app.use. This allows for more granular control over which requests are proxied. ```javascript app.use( createProxyMiddleware({ target: 'http://www.example.org/api', changeOrigin: true, pathFilter: '/api/proxy-only-this-path', }), ); ``` -------------------------------- ### WebSocket Proxy with Path Rewrite Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/websocket.md Configure a WebSocket proxy middleware that includes path rewriting capabilities. The `pathRewrite` option modifies the URL before proxying. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; const options = { target: 'http://localhost:3000', ws: true, pathFilter: '/socket', pathRewrite: { '^/socket': '', }, }; const socketProxy = createProxyMiddleware(options); ``` -------------------------------- ### Plugins: Ejecting Default Plugins Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Eject default plugins and manually add them back along with custom ones. This provides full control over the plugin pipeline. Ensure error handling plugins are included to prevent server crashes. ```javascript import { debugProxyErrorsPlugin, // subscribe to proxy errors to prevent server from crashing errorResponsePlugin, // return 5xx response on proxy error loggerPlugin, // log proxy events to a logger (ie. console) proxyEventsPlugin, // implements the "on:" option } from 'http-proxy-middleware'; createProxyMiddleware({ target: `http://example.org`, changeOrigin: true, ejectPlugins: true, plugins: [debugProxyErrorsPlugin, loggerPlugin, errorResponsePlugin, proxyEventsPlugin], }); ``` -------------------------------- ### Proxying with Request Body Buffering Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Use the `buffer` option to provide a stream of data for the request body when the request stream has been consumed by middleware. Requires `stream-array` for creating the stream. ```javascript import { createProxyServer } from 'httpxy'; import streamify from 'stream-array'; const proxy = createProxyServer(); export default function proxyWithBody(req, res, next) { proxy.web( req, res, { target: 'http://127.0.0.1:4003/', buffer: streamify(req.rawBody), }, next, ); } ``` -------------------------------- ### Add Request Headers with onProxyReq Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Use the onProxyReq event to add custom headers to the outgoing request to the target server or to log request details. ```javascript function onProxyReq(proxyReq, req, res) { // add custom header to request proxyReq.setHeader('x-added', 'foobar'); // or log the req } ``` -------------------------------- ### WebSocket Client Connection and Messaging Source: https://github.com/chimurai/http-proxy-middleware/blob/master/examples/websocket/index.html Handles WebSocket lifecycle events including connection, disconnection, and message transmission within a browser environment. ```javascript window.onload = function () { // elements const configuration = document.getElementById('configuration'); const location = document.getElementById('location'); const codeblockWsLocation = document.getElementById('codeblock-ws-location'); const connectBtn = document.getElementById('connectBtn'); const disconnectBtn = document.getElementById('disconnectBtn'); const messaging = document.getElementById('messaging'); const message = document.getElementById('message'); const sendBtn = document.getElementById('sendBtn'); const logger = document.getElementById('logger'); const documentUrl = new URL(document.location); const wsProtocol = documentUrl.protocol.includes('https') ? 'wss:' : 'ws:'; const wsPort = documentUrl.port ? `${documentUrl.port}` : ''; const locationValue = `${wsProtocol}//${documentUrl.host}${wsPort}`; location.value = locationValue; codeblockWsLocation.innerText = locationValue; // ws let socket; connectBtn.onclick = () => { connect(); }; disconnectBtn.onclick = () => { disconnect(); }; sendBtn.onclick = () => { sendMessage(message.value); }; function connect() { setupSocket(location.value); toggleControls(); } function disconnect() { socket.close(); socket = undefined; toggleControls(); } function sendMessage(val) { log('SEND: ' + val); socket.send(val); } function setupSocket(url) { socket = new WebSocket(url); socket.addEventListener('open', () => { log('CONNECTED'); }); socket.addEventListener('close', () => { log('DISCONNECTED'); }); socket.addEventListener('error', () => { log('SOCKET ERROR OCCURRED'); }); socket.addEventListener('message', (msg) => { log('RECEIVED:' + msg.data); }); } function log(message) { logger.value = logger.value + message + '\n'; logger.scrollTop = logger.scrollHeight; // scroll to bottom } function toggleControls() { [connectBtn, disconnectBtn, messaging].forEach((el) => toggleEnabled(el)); } function toggleEnabled(el) { el.disabled = el.disabled ? false : true; } }; ``` -------------------------------- ### HTTPS Server Proxy with Client Certificate Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/https.md Proxy requests to an HTTPS server that requires a client certificate for authentication. The certificate and passphrase are provided via the 'pfx' and 'passphrase' options. ```javascript import * as fs from 'node:fs'; import { createProxyMiddleware } from 'http-proxy-middleware'; const apiProxy = createProxyMiddleware({ target: { protocol: 'https:', host: 'example.org', port: 443, pfx: fs.readFileSync('path/to/certificate.p12'), passphrase: 'password', }, changeOrigin: true, }); ``` -------------------------------- ### Manipulate Image Responses with Jimp Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/response-interceptor.md Process image responses using the Jimp library for manipulations like flipping, sepia, and pixelation. Requires 'selfHandleResponse' to be true and checks for common image content types. ```javascript // use jimp library for image manipulation import { createProxyMiddleware, responseInterceptor } from 'http-proxy-middleware'; import Jimp from 'jimp'; const proxy = createProxyMiddleware({ target: 'https://upload.wikimedia.org', changeOrigin: true, // for vhosted sites selfHandleResponse: true, // res.end() will be called internally by responseInterceptor() on: { proxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => { const imageTypes = ['image/png', 'image/jpg', 'image/jpeg', 'image/gif']; // detect image responses if (imageTypes.includes(proxyRes.headers['content-type'])) { try { const image = await Jimp.read(responseBuffer); image.flip(true, false).sepia().pixelate(5); return image.getBufferAsync(Jimp.AUTO); } catch (err) { console.log('image processing error: ', err); return responseBuffer; } } return responseBuffer; // return other content-types as-is }), }, }); // http://localhost:3000/wikipedia/en/7/7d/Lenna\_%28test_image%29.png ``` -------------------------------- ### Implement custom path filtering Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathFilter.md Provides a function to evaluate the pathname and request object for granular control. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; const pathFilter = function (pathname, req) { return pathname.match('^/api') && req.method === 'GET'; }; const apiProxy = createProxyMiddleware({ pathFilter: pathFilter, target: 'http://localhost:3000', }); ``` -------------------------------- ### Router: Custom Function (String Target) Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Define a custom router function that returns a target URL string. This provides dynamic routing logic based on request details. ```javascript router: function(req, res, options) { return 'http://127.0.0.1:8004'; } ``` -------------------------------- ### Express Server with Proxy Middleware Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Integrate http-proxy-middleware into an Express server to proxy requests to a specific API endpoint. Ensure the target includes the base path if necessary. ```javascript // include dependencies import express from 'express'; import { createProxyMiddleware } from 'http-proxy-middleware'; const app = express(); // create the proxy /** @type {import('http-proxy-middleware').RequestHandler} */ const exampleProxy = createProxyMiddleware({ target: 'http://www.example.org/api', // target host with the same base path changeOrigin: true, // needed for virtual hosted sites }); // mount `exampleProxy` in web server app.use('/api', exampleProxy); app.listen(3000); ``` -------------------------------- ### Custom Path Rewrite Function Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathRewrite.md Implement custom path rewrite logic using a function. The function receives the path, request, response, and options. Returning 'undefined' uses the original path. Note that 'res' is undefined in WebSocket upgrade flows. ```javascript import { createProxyMiddleware } from 'http-proxy-middleware'; const rewriteFn = function (path, req, res, options) { return path.replace('/api/foo', '/api/bar'); }; const options = { target: 'http://localhost:3000', pathRewrite: rewriteFn, }; const apiProxy = createProxyMiddleware(options); // `/api/foo/lorum/ipsum` -> `http://localhost:3000/api/bar/lorum/ipsum` // NOTE: `res` is undefined in WebSocket upgrade flows. ``` -------------------------------- ### Router: Asynchronous Function Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Implement asynchronous routing logic using a function that returns a Promise. This enables I/O operations to determine the target URL. ```javascript router: async function(req, res, options) { const url = await doSomeIO(); return url; } ``` -------------------------------- ### Next.js API Route Handler Using Proxy Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md Create a Next.js API route handler that utilizes the pre-defined proxy middleware. Configure API route settings for external resolvers and body parsing. ```typescript // Next project: `/pages/api/users.ts` // Next.js API route support: https://nextjs.org/docs/api-routes/introduction import type { NextApiRequest, NextApiResponse } from 'next'; import { proxyMiddleware } from './users.proxy'; export default function handler(req: NextApiRequest, res: NextApiResponse) { proxyMiddleware(req, res, (result: unknown) => { if (result instanceof Error) { throw result; } }); } export const config = { api: { externalResolver: true, // Uncomment to fix stalled POST requests // https://github.com/chimurai/http-proxy-middleware/issues/795#issuecomment-1314464432 // bodyParser: false, }, }; // curl http://localhost:3000/api/users ``` -------------------------------- ### Custom Router Function Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/router.md Use a custom router function to dynamically determine the target for a request. The function receives request, response, and options, and should return the target URL. ```javascript import express from 'express'; import { createProxyMiddleware } from 'http-proxy-middleware'; const customRouter = function (req, res, options) { options.headers = { ...options.headers, 'x-routing-strategy': 'custom-router', }; return 'http://www.example.org'; // protocol + host }; const options = { target: 'http://localhost:8000', router: customRouter, }; const myProxy = createProxyMiddleware(options); const app = express(); app.use(myProxy); // add the proxy to express app.listen(3000); // NOTE: `res` is undefined in WebSocket upgrade flows. ``` -------------------------------- ### Custom Path Filter Function Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Use a custom function for path filtering to determine which requests should be proxied based on path and request method. Ensure the function returns a boolean. ```javascript const pathFilter = function (path, req) { return path.match('^/api') && req.method === 'GET'; }; const apiProxy = createProxyMiddleware({ target: 'http://www.example.org', pathFilter: pathFilter, }); ``` -------------------------------- ### Next.js API Route Proxy Middleware Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md Define a proxy middleware for Next.js API routes. This is a singleton that can be reused across different API handlers. ```typescript // Next project: `/pages/api/users.proxy.ts` import { createProxyMiddleware } from 'http-proxy-middleware'; // singleton export const proxyMiddleware = createProxyMiddleware({ target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, pathRewrite: { '^/api/users': '/users', }, }); ``` -------------------------------- ### Proxy API Requests with Express Source: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md Use this snippet to proxy API requests from your Express server to a target backend. Ensure 'changeOrigin' is set to true for virtual hosted sites. ```typescript import express from 'express'; import type { NextFunction, Request, Response } from 'express'; import { createProxyMiddleware } from 'http-proxy-middleware'; import type { Filter, Options, RequestHandler } from 'http-proxy-middleware'; const app = express(); const proxyMiddleware = createProxyMiddleware({ target: 'http://www.example.org/api', changeOrigin: true, }); app.use('/api', proxyMiddleware); app.listen(3000); // proxy and keep the same base path "/api" // http://127.0.0.1:3000/api/foo/bar -> http://www.example.org/api/foo/bar ``` -------------------------------- ### Modify Request Headers Asynchronously with Middleware Source: https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/async-response.md Apply middleware before the proxy to modify request headers asynchronously. The middleware can set data on `req.locals` which can then be accessed in the `proxyReq` event handler. ```javascript const entryMiddleware = async (req, res, next) => { const foo = await new Promise((resolve, reject) => { setTimeout(() => { resolve({ da: 'da' }); }, 200); }); req.locals = { da: foo.da, }; next(); }; const myProxy = createProxyMiddleware({ target: 'http://www.example.com/api', changeOrigin: true, selfHandleResponse: true, on: { proxyReq: (proxyReq, req, res) => { // before // get something async from entry middleware before the proxy kicks in console.log('proxyReq:', req.locals.da); proxyReq.setHeader('mpth-1', req.locals.da); }, proxyRes: async (proxyRes, req, res) => { const da = await new Promise((resolve, reject) => { setTimeout(() => { resolve({ wei: 'wei' }); }, 200); }); // end: res.setHeader('mpth-2', da.wei); proxyRes.pipe(res); }, }, }); app.use('/api', entryMiddleware, myProxy); ```