> 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/chat/example-minimal-chat/javascript-typescript.md). Agents can also search and read this documentation through its [MCP server](https://dnotifier.gitbook.io/product-docs/~gitbook/mcp).

# JavaScript / TypeScript

Full walkthrough: two-user 1:1 chat with history, send, and receive.

***

## Bob — receiver (Terminal 1)

Save as `bob.js`:

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

const MY_USER_ID = "user-bob";
const PEER_USER_ID = "user-alice";
const messages = [];

const notifier = new DNotifier({
  appId: process.env.DNOTIFIER_APP_ID,
  secret: process.env.DNOTIFIER_SECRET,
  transport: "ws",
  userId: MY_USER_ID,
  WebSocketImpl: WebSocket,
  onConnected: async () => {
    console.log("Bob online");
    await notifier.fetchChatHistory({
      senderId: MY_USER_ID,
      receiverIds: [PEER_USER_ID],
    });
  },
  onMessage: (msg) => {
    const body = msg.payload.toJSON();

    if (Array.isArray(body?.messages)) {
      body.messages.forEach((m) => messages.push(m));
      console.log(`[history] ${body.messages.length} messages loaded`);
      messages.forEach(printMessage);
      return;
    }

    if (body?.type === "text") {
      const entry = {
        sender: msg.metadata.sender,
        text: body.text,
        timestamp: msg.metadata.timestamp,
      };
      messages.push(entry);
      printMessage(entry);
    }
  },
  onDisconnected: ({ reason }) => console.log("Bob offline:", reason),
});

function printMessage(m) {
  console.log(`  ${m.sender}: ${m.text}`);
}

await notifier.connect();
```

Run: `node bob.js`

***

## Alice — sender with REPL (Terminal 2)

Save as `alice.js`:

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

const MY_USER_ID = "user-alice";
const PEER_USER_ID = "user-bob";

const notifier = new DNotifier({
  appId: process.env.DNOTIFIER_APP_ID,
  secret: process.env.DNOTIFIER_SECRET,
  transport: "ws",
  userId: MY_USER_ID,
  WebSocketImpl: WebSocket,
  onConnected: async () => {
    console.log("Alice online — type a message and press Enter");
    await notifier.fetchChatHistory({
      senderId: MY_USER_ID,
      receiverIds: [PEER_USER_ID],
    });
  },
  onMessage: (msg) => {
    const body = msg.payload.toJSON();
    if (Array.isArray(body?.messages)) {
      console.log(`[history] ${body.messages.length} messages`);
      return;
    }
    if (body?.type === "text") {
      console.log(`← ${msg.metadata.sender}: ${body.text}`);
    }
  },
  onDisconnected: ({ reason }) => console.log("Alice offline:", reason),
});

await notifier.connect();

const rl = readline.createInterface({ input: process.stdin, output: process.stdout });

rl.on("line", async (line) => {
  const text = line.trim();
  if (!text) return;

  try {
    await notifier.send({
      senderId: MY_USER_ID,
      receiverId: PEER_USER_ID,
      data: { type: "text", text },
    });
    console.log(`→ you: ${text}`);
  } catch (err) {
    console.error("Send failed:", err.message);
  }
});
```

Run: `node alice.js`

***

## Expected flow

1. Start bob → `Bob online`
2. Start alice → `Alice online`
3. Alice types `Hello Bob!` → bob prints `alice: Hello Bob!`
4. Bob types in his own client if you add a REPL, or alice sends again
5. Restart alice → `[history]` shows prior messages

***

## Browser variant (single page)

For a browser demo, bind a form to `send()` and render `onMessage` into a `<div id="messages">`. Omit `WebSocketImpl` and use Vite/env for credentials.

***

## Troubleshooting

| Issue                   | Fix                                                                     |
| ----------------------- | ----------------------------------------------------------------------- |
| Bob never receives      | Same `appId`; bob must be running before alice sends                    |
| Empty history           | First conversation — history fills after first `saveHistory: true` send |
| `Not connected` on send | Wait for `onConnected`                                                  |

***

## Learn more

* [Building 1:1 chat](https://dnotifier.gitbook.io/product-docs/chat/building-one-to-one-chat/javascript-typescript.md)
* [Chat UI patterns](https://dnotifier.gitbook.io/product-docs/chat/ui-patterns.md)
