---
title: Listen from Node.js
project: OpenSync
version: 1.0
section: recipes
language: en
license: MIT
url: https://totaljs.es/docs/opensync/1-0/recipes/nodejs-client/
updated: 2026-11-19T09:22:09.965Z
---

# Listen from Node.js

> A small Node.js script that receives the messages and reconnects when the connection drops.

Node.js 22 and later have a built-in `WebSocket`, so this script needs no packages.

## The script

Save it as `listen.js`, with your address and token:

```js
const URL = 'wss://sync.example.com/?token=YOUR_TOKEN&app=Warehouse';

function connect() {
	const ws = new WebSocket(URL);

	ws.onmessage = function(e) {
		const msg = JSON.parse(e.data);
		if (msg.type === 'init') {
			console.log('Connected to', msg.name);
			return;
		}
		console.log(msg.channel, msg.method, JSON.stringify(msg.body));
	};

	ws.onclose = function() {
		console.log('Disconnected, trying again in 3 seconds');
		setTimeout(connect, 3000);
	};
}

connect();
```

## Run it

```bash
node listen.js
```

Send an order, then remove it:

```bash
curl -X POST -H "Content-Type: application/json" -d '{"id":1002,"status":"paid"}' "https://sync.example.com/sync/orders/"
curl -X DELETE "https://sync.example.com/sync/orders/?id=1002"
```

The script prints, also across a restart of OpenSync:

```text
Connected to Demo sync
orders POST {"id":1002,"status":"paid"}
Disconnected, trying again in 3 seconds
Connected to Demo sync
orders DELETE ""
```

Messages sent while the script was disconnected are not delivered later.

## Send from the same script

To send a message to the other clients, call `send` on the open connection:

```js
ws.send(JSON.stringify({ type: 'notify', channel: 'chat', body: { text: 'Hello' } }));
```

See [WebSocket](../../reference/websocket/).
