Skip to content

Memory leak #365

@KidkArolis

Description

@KidkArolis

We've experience a serious memory leak issue when using this package. This was only introduced in some version >=0.8, with ^0.7 it used to be fine.

We haven't found the root of cause and I don't have a reproducible example, if it helps, we've used the following options:

reqBodyEncoding: null,
limit: '10mb',
memoizeHost: false,
proxyReqOptDecorator
proxyReqPathResolver
userResDecorator
proxyErrorHandler

image

We've fixed it by replacing the package with the following code (in case it helps anyone else):

const url = require('url')
const Boom = require('boom')
const http = require('http')
const https = require('https')

const ENV = process.env.NODE_ENV || 'development'

module.exports = function proxy (host) {
  return (req, res, next) => {
    const targetUrl = url.resolve(req.host, req.originalUrl)
    const parsed = url.parse(targetUrl)

    const reqOpts = {
      host: parsed.hostname,
      port: parsed.port,
      path: parsed.path,
      method: req.method,
      headers: { ...req.headers }
    }
    delete reqOpts.headers.host

    const agent = parsed.protocol === 'https:' ? https : http

    const proxyReq = agent.request(reqOpts, async (proxyRes) => {
      const isBadStatusCode = proxyRes.statusCode >= 500
      if (ENV === 'production' && isBadStatusCode) {
        // don't leak information in prod
        return next(new Boom(new Error('Bad gateway'), { statusCode: proxyRes.statusCode }))
      }

      res.status(proxyRes.statusCode)
      Object.keys(proxyRes.headers)
        // https://github.com/CoreFiling/express-http-proxy/pull/1
        .filter(header => header !== 'transfer-encoding')
        .forEach(header => res.set(header, proxyRes.headers[header]))

      proxyRes.pipe(res)
      proxyRes.on('error', next)
    })
    proxyReq.on('error', next)

    req.pipe(proxyReq)
    req.on('aborted', () => proxyReq.abort())
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions