> For the complete documentation index, see [llms.txt](https://dnotifier.gitbook.io/product-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dnotifier.gitbook.io/product-docs/realtime-communication/binary-messaging/javascript-typescript.md).

# JavaScript / TypeScript

Send raw bytes with `sendBinary()`.

***

## Basic example

```js
import WebSocket from "ws";
import { DNotifier } from "@dnotifier-realtime/dnotifier";

const notifier = new DNotifier({
  appId: process.env.DNOTIFIER_APP_ID,
  secret: process.env.DNOTIFIER_SECRET,
  transport: "ws",
  userId: "user-alice",
  WebSocketImpl: WebSocket,
  onConnected: () => {},
  onMessage: (msg) => {
    if (msg.metadata.type === "binary") {
      const bytes = msg.payload.raw();
      console.log("Binary frame:", bytes.length, "bytes");
      return;
    }
    console.log(msg.payload.toJSON());
  },
  onDisconnected: () => {},
});

await notifier.connect();

notifier.sendBinary({
  senderId: "user-alice",
  receiverIds: ["user-bob"],
  buffer: new Uint8Array([0x00, 0x01, 0x02, 0xff]),
  type: "binary",
});
```

***

## Multiple receivers

```js
notifier.sendBinary({
  senderId: "user-alice",
  receiverIds: ["user-bob", "user-carol"],
  buffer: compressedStateBuffer,
  type: "binary",
});
```

***

## Custom protocol example

```js
function encodeCursorOp(x, y) {
  const buffer = new ArrayBuffer(8);
  const view = new DataView(buffer);
  view.setFloat32(0, x);
  view.setFloat32(4, y);
  return new Uint8Array(buffer);
}

notifier.sendBinary({
  senderId: myUserId,
  receiverIds: [peerUserId],
  buffer: encodeCursorOp(120.5, 340.0),
  type: "binary",
});
```

Receiver:

```js
onMessage: (msg) => {
  const raw = msg.payload.raw();
  const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
  const x = view.getFloat32(0);
  const y = view.getFloat32(4);
  updatePeerCursor(x, y);
},
```

***

## Node.js Buffer

```js
import { Buffer } from "buffer";

notifier.sendBinary({
  senderId: "user-alice",
  receiverIds: ["user-bob"],
  buffer: Buffer.from([0xde, 0xad, 0xbe, 0xef]),
});
```

The SDK accepts `Uint8Array`, `Buffer`, and array-like byte sources.

***

## Troubleshooting

| Issue                                | Check                                       |
| ------------------------------------ | ------------------------------------------- |
| Receiver gets JSON instead of binary | Confirm you called `sendBinary`, not `send` |
| `receiverIds required`               | Pass a non-empty array                      |
| Garbled bytes on receive             | Use `payload.raw()`, not `toJSON()`         |

***

## Learn more

* [Structured payloads](https://dnotifier.gitbook.io/product-docs/realtime-communication/structured-payloads/javascript-typescript.md)
* [Large messages & chunking](https://dnotifier.gitbook.io/product-docs/realtime-communication/chunking.md)
