I have a nginx web server running on my raspberry PI. In the webserver I have a React App, and a node server on the backend. When I run this locally, everything works great. But I am stumped on getting the virtualhost configuration to be able to utilize and reach the websocket server. I've tried a million things, and I'm about ready to repurpose this raspberry PI back over to my 3d printer if I can't get this figured out.
Here are the bits of code that should be relevant to this problem.
On the FRONTEND:
import useWebSocket, { ReadyState } from 'react-use-websocket';
const WS_URL = wss://localhost:3000/ws; I have also tried ws://localhost:3000.
NODE Server code:
const { WebSocket, WebSocketServer } = require('ws');
const http = require('http');
require('dotenv').config();
// Spinning the http server, the WebSocket server, and initiating Redis.
const server = http.createServer();
const wsServer = new WebSocketServer({ server });
const port = 3000;
const redis = createClient({
url: process.env.REDIS_CONNECTION_URL
});
redis.on('error', err => console.log('Redis Client Error', err));
server.listen(port, async () => {
await redis.connect();
console.log(`WebSocket server is running on port ${port}`);
});
And last, but certainly not least is the nginx conf.
server {
server_name stef.page www.stef.page;
root /var/www/stef.page/build;
index index.html;
location /ws {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/stef.page/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/stef.page/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.stef.page) {
return 301 https://$host$request_uri;
} # managed by Certbot
if ($host = stef.page) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
listen [::]:80;
server_name stef.page www.stef.page;
return 404; # managed by Certbot
}
When I run 'node index.js' the response is satisfactory. Everything seems to be running. But on the client, the error i'm currently receiving on this configuration is: WebSocket connection to 'wss://localhost:3000/ws' failed
If your client is not the Pi then you need to update your websocket url to use the hostname or IP address of the Pi instead of
localhost. It works fine locally because the client and the server are both running on the same host. But the client (presumably the browser) itself on your PC is localhost when trying to initiate the websocket connection, thus it's trying to open a web socket on your PC and not the Pi.