> 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/chat-history/javascript-typescript.md).

# JavaScript / TypeScript

Fetch and render chat history with `fetchChatHistory`.

***

## Fetch on thread open

```js
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 () => {
    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(`Loaded ${body.messages.length} history messages`);
      renderHistory(body.messages);
      return;
    }

    // Live message
    if (body?.type === "text") {
      appendLiveMessage(msg.metadata, body);
    }
  },
  onDisconnected: () => {},
});

await notifier.connect();
```

***

## Merge history with live messages

```js
const messageMap = new Map();

function upsertMessage(msg) {
  const id = msg.id ?? `${msg.sender}_${msg.timestamp}`;
  messageMap.set(id, msg);
  renderSorted([...messageMap.values()]);
}

onMessage: (msg) => {
  const body = msg.payload.toJSON();

  if (Array.isArray(body?.messages)) {
    body.messages.forEach(upsertMessage);
    return;
  }

  if (body?.type === "text") {
    upsertMessage({
      id: msg.metadata.id,
      sender: msg.metadata.sender,
      text: body.text,
      timestamp: msg.metadata.timestamp,
    });
  }
},
```

***

## Refetch after reconnect

```js
async function onReconnect() {
  await notifier.connect();
  await notifier.fetchChatHistory({
    senderId: MY_USER_ID,
    receiverIds: [PEER_USER_ID],
  });
}
```

***

## Troubleshooting

| Issue                     | Check                                                        |
| ------------------------- | ------------------------------------------------------------ |
| No history in `onMessage` | Confirm `saveHistory: true` was used when messages were sent |
| Empty array               | Thread may have no persisted messages yet                    |
| `Not connected`           | Call after `connect()` succeeds                              |
| Duplicate messages        | Deduplicate by `metadata.id` when merging history + live     |

***

## Learn more

* [Save history flag](https://dnotifier.gitbook.io/product-docs/chat/save-history.md)
* [Delete chat messages](https://dnotifier.gitbook.io/product-docs/chat/delete-messages/javascript-typescript.md)
