I use http-proxy-middleware in a NestJS middleware to proxy / rewrite some requests. Problem is, for every request on that route, a new Instance of the Middleware Class is created. After a couple of requests the whole application will crash because the memory is full and I get a "javascript head out of memory" error. Any ideas how I can fix this?
@Injectable()
export class MyProxyMiddleware implements NestMiddleware {
private proxy: RequestHandler;
constructor(
private readonly exampleService: ExampleService,
) {
this.proxy = createProxyMiddleware(this.options);
}
private readonly options = {
...
onProxyReq: (proxyReq, req) => this.setRequestHeaders(proxyReq, req),
onProxyRes: (proxyRes, req, res) =>
this.appendResponseHeaders(proxyRes, req, res),
};
async rewrite(path) {
const resolved = await this.exampleService.resolve();
// rewrite
} catch (e) {
throw e;
}
}
setRequestHeaders(proxyReq, req) {
Object.keys(req.headers).forEach((key) => {
proxyReq.setHeader(key, req.headers[key]);
});
}
appendResponseHeaders(proxyRes, req, res) {
Object.keys(proxyRes.headers).forEach((key) => {
res.append(key, proxyRes.headers[key]);
});
}
use(req, res, next: () => void) {
this.proxy(req, res, next);
}
}
I already tried to move the createProxyMiddleware() function call from the use function to the constructor of the class, hoping to create only one instance of the proxy, but with no luck.
app.module.ts
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(MyProxyMiddleware).forRoutes({
path: '/environments/*/documents/*/text*',
method: RequestMethod.ALL,
});
}