Serial. Ws | Extended & Genuine
While serial.ws is powerful, it introduces new attack surfaces. Here is how to secure it:
Even robust bridges hit problems. Here is a cheat sheet for serial.ws debugging:
| Symptom | Likely Cause | Solution |
|---------|--------------|----------|
| Error: Port not found | Wrong serial path | List ports: SerialPort.list() or check /dev/tty* / Device Manager |
| WebSocket connects but no data | Buffering or line endings | Ensure device sends newline (\n). Add port.setEncoding('utf8') |
| Data corruption | Baud rate mismatch | Verify device and bridge share exact baud rate (e.g., 9600, 115200) |
| Connection drops randomly | Idle timeout | Send heartbeat ping/pong every 30 seconds |
<!DOCTYPE html> <html> <head> <title>serial.ws Client</title> </head> <body> <textarea id="output" rows="10" cols="50"></textarea> <input type="text" id="command" placeholder="Send command..."> <button onclick="sendCommand()">Send</button><script> const socket = new WebSocket('ws://localhost:8080'); const output = document.getElementById('output'); socket.onmessage = (event) => output.value += event.data + '\n'; output.scrollTop = output.scrollHeight; ; function sendCommand() const cmd = document.getElementById('command').value; socket.send(cmd); </script>
</body> </html>
Run node bridge.js and open index.html. You now have a working serial.ws system.
This is where serial.ws enters. Instead of the browser talking directly to the OS, it talks to a WebSocket server (often running locally or on a network device). That server holds the actual serial connection.
// serial.ws approach
const socket = new WebSocket('ws://localhost:8080/serial');
socket.onmessage = (event) =>
console.log('Serial data:', event.data);
;
socket.send('AT+CMD\r\n');
The advantage: Any web client that can speak WebSockets (browsers, mobile apps, even other servers) can now interact with the serial device remotely.
What if your serial device is connected to a Raspberry Pi in another room? The native Web Serial API cannot see network-attached serial ports. However, a serial.ws server running on that remote Pi can expose the serial stream over Wi-Fi or Ethernet, allowing any browser on the same network to connect. serial. ws
const WebSocket = require('ws'); const SerialPort = require('serialport');// Configure your serial port (change path and baudRate as needed) const port = new SerialPort( path: '/dev/ttyUSB0', // Windows: 'COM3' baudRate: 9600 );
const wss = new WebSocket.Server( port: 8080 );
wss.on('connection', (ws) => console.log('WebSocket client connected to serial.ws');
// Forward serial data -> WebSocket clients port.on('data', (data) => ws.send(data.toString('utf8')); ); While serial
// Forward WebSocket messages -> Serial device ws.on('message', (message) => port.write(message.toString() + '\r\n'); );
ws.on('close', () => console.log('Client disconnected'); ); );
console.log('serial.ws bridge running on ws://localhost:8080');