Angular CLI: Proxy websocket with proxy.conf.json

j3ff Source

I am trying to proxy websockets using ng serve --proxy-config proxy.conf.json with Angular CLI but could'nt get it to work as I am getting this error:

WebSocket connection to 'ws://stream/connect' failed: Error in connection establishment: net::ERR_NAME_NOT_RESOLVED

Here is how I instantiated the websocket and my proxy configuration:

// WebSocket instantiation
const ws = new WebSocket('ws://stream/connect');

// proxy.conf.json
"stream/**": {
  "target": "wss://",
  "secure": false,
  "ws": true

Am I missing something? It seems to be doable but i can't get it to work correctly!

This closed issue did not helped neither did this stackoverflow answer.



answered 6 months ago j3ff #1

I figured it out! If it can help anyone...

By default Angular CLI runs the application on port 4200 and proxy is listening on that same port... therefore I should do:

// websocket instantiation
const ws = new WebSocket('ws://localhost:4200/stream/connect');

// proxy.conf.json
"/stream/*": {
  "target": "",
  "secure": false,
  "ws": true

Hardcoding localhost:4200 in the WebSocket constructor wouldn't work in every deployed environment because the url on which the proxy is listening would differs... so I came up with getting the location host and protocol dynamically and used it in the WebSocket constructor:

// set ws protocol when using http and wss when using https
const protocol = window.location.protocol.replace('http', 'ws');
// get location host
const host =;
// websocket instantiation
const ws = new WebSocket(`${protocol}//${host}/stream/connect`);

And BAM ... voilà!! 🎊 🎉 👏

comments powered by Disqus