Question
Issue emitting socket.io messages on Ubuntu droplet
I recently moved my API:s from Heroku to a Ubuntu droplet provided by digital ocean. I followed these instructions on how to deploy my Node.js/Express API:s and got all of my endpoints working as expected. The only issue is that im able to connect/disconnect to the socket, but not able to emit any messages through the websockets. Everything works fine locally & in heroku with the same code, so I think the issue might be with nginx or ufw firewall.
Client code:
const socket = socketIOClient(https://www.myapp.com/api-with-websockets);
socket.connect();
socket.emit('joinChannel', conversation.id);
Backend:
io.on("connection", (socket) => {
console.log("New client connected");
socket.on("joinChannel", (msg) => {
console.log("New client joined channel:", msg); // <-- never gets called
socket.join(msg);
});
socket.on("disconnect", () => {
console.log("Client disconnected");
});
});
nginx conf:
server {
root /var/www/myapp.com/html;
index index.html index.htm index.nginx-debian.html;
server_name myapp.com www.myapp.com;
location / {
try_files $uri $uri/ =404;
}
location /api-with-websockets/ {
proxy_pass http://localhost:3001/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
location /no-websockets-api/ {
proxy_pass http://localhost:3003/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
location ~ ^/(socket\.io) {
proxy_pass http://localhost:3001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/myapp.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/myapp.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = www.myapp.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
if ($host = myapp.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
listen [::]:80;
server_name myapp.com www.myapp.com;
return 404; # managed by Certbot
}
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
×