Package detail

koa-proxies

vagusX79kMIT0.12.4

Http Proxy Middleware for Koa@2.x/next

koa, middleware, proxy, proxies

readme

Koa Proxies

NPM

Node.js CI Coverage NPM Downloads Greenkeeper badge

Koa@2.x/next middlware for http proxy

Powered by http-proxy.

Installation

$ npm install koa-proxies --save

Options

http-proxy events

options.events = {
  error (err, req, res) { },
  proxyReq (proxyReq, req, res) { },
  proxyRes (proxyRes, req, res) { }
}

log option

// enable log
options.logs = true; // or false

// custom log function
options.logs = (ctx, target) {
  console.log('%s - %s %s proxy to -> %s', new Date().toISOString(), ctx.req.method, ctx.req.oldPath, new URL(ctx.req.url, target))
}

Usage

// dependencies
const Koa = require('koa')
const proxy = require('koa-proxies')
const httpsProxyAgent = require('https-proxy-agent')

const app = new Koa()

// middleware
app.use(proxy('/octocat', {
  target: 'https://api.github.com/users/',
  changeOrigin: true,
  agent: new httpsProxyAgent('http://1.2.3.4:88'), // if you need or just delete this line
  rewrite: path => path.replace(/^\/octocat(\/|\/\w+)?$/, '/vagusx'),
  logs: true
}))

The 2nd parameter options can be a function. It will be called with the path matching result (see path-match for details) and Koa ctx object. You can leverage this feature to dynamically set proxy. Here is an example:

// dependencies
const Koa = require('koa')
const proxy = require('koa-proxies')

const app = new Koa()

// middleware
app.use(proxy('/octocat/:name', (params, ctx) => {
  return {
    target: 'https://api.github.com/',
    changeOrigin: true,
    rewrite: () => `/users/${params.name}`,
    logs: true
  }})
)

Moreover, if the options function return false, then the proxy will be bypassed. This allows the middleware to bail out even if path matching succeeds, which could be helpful if you need complex logic to determine whether to proxy or not.

Attention

Please make sure that koa-proxies is in front of koa-bodyparser to avoid this issue 55

const Koa = require('koa')
const app = new Koa()
const proxy = require('koa-proxies')
const bodyParser = require('koa-bodyparser')

app.use(proxy('/user', {
  target: 'http://example.com',
  changeOrigin: true
}))

app.use(bodyParser())

JavaScript Style Guide

changelog

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

0.12.4 (2023-11-04)

Features

  • options function return false, fix default logger (#74) (9928ae1)

0.12.3 (2022-12-05)

Features

  • call events.error handler from error callback (#70) (b14e202)

0.12.2 (2022-02-23)

Bug Fixes

  • support multiple event listeners (#66) (94e2f16)

0.12.1 (2021-04-08)

Bug Fixes

  • add samples to npm ignore (3a623f2)

0.12.0 (2021-04-08)

Bug Fixes

0.0.1 - 2016-12-19

Initial release