How to handle ws requests in reverse proxy

Describe the problem/error/question

We are using n8n as self-hosted, we implemented a reverse-proxy service (based on node js) which serve all API and UI requests. now we encounter the UI is basing also on web socket requests and i wonder if anyone succeded to handle the ws://... requests using reverse-proxy which implemented with NestJS

What is the error message (if any)?

WebSocket stuck on pending when browser init the request. see attached image

Information on your n8n setup

  • **n8n version:lates
  • **Database (default: SQLite):postgres
  • n8n EXECUTIONS_PROCESS setting (default: own, main):
  • **Running n8n via (Docker, npm, n8n cloud, desktop app):npm
  • Operating system:

Hey @mtubul,

I have never tried with NestJS as I have only used “off the shelve” reverse proxies. Is there anything in the Nest docs around what to do?

In case someone will need this kind of solution, eventally i solved it as follows

  1. Create a middleware
  2. using http-proxy-middleware to proxy the ws requests

code example :

import { createProxyMiddleware } from 'http-proxy-middleware';

@Injectable()
export class WebsocketMiddleware implements NestMiddleware {
  private readonly proxy: any;
  constructor(private ciamGuard: CiamPlatformGuard) {
    const host = process.env.WORKFLOWS_SERVER_URL.split('http:')[1];
    this.proxy = createProxyMiddleware({
      target: `ws:${host}`,
      secure: false,
      changeOrigin: true,
      ws: true,
    });
  }
  async use(req: any, res: any, next: () => void): Promise<any> {
    // proxy only websocket requests otherwise continue to our controller
    if (req.headers['upgrade'] !== 'websocket') {
      return next();
    }
    try {
      // validate websocket cookie
      if (await this.ciamGuard.authenticate(req)) {
        return this.proxy(req, res, next);
      }
    } catch (e) {
      logger.error(e);
      return next();
    }
  }
}
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.