"I want two laptops to chat in the browser using nothing but Bluetooth." The obvious approach is for one browser to open a Bluetooth connection to the other. Today's browsers cannot do that. This article starts the design from why they can't, then builds a chat that puts an ESP32 in the middle as a relay, using code that has been checked with unit tests and a compiler.
What you will learn
- Why browsers cannot connect to each other over Bluetooth, and the design that uses an ESP32 as a relay
- GATT layout, ATT_MTU and payload size, and splitting and reassembling UTF-8
- Message IDs and sender IDs, duplicate suppression, application-layer acknowledgements and retries, and recovering from disconnects
- Limits on simultaneous connections and buffers, pairing and encryption, and a threat model
- How this compares with WebRTC and other options, and criteria for adopting it in production
The short answer: A browser can only be a BLE Central (a GATT client). So both browsers connect, as Centrals, to an ESP32 acting as a Peripheral (a GATT server), and the ESP32 forwards each browser's writes to the other as notifications. A successful BLE write only means "the relay got it", so the application layer needs its own mechanism: the receiving app sends an ACK and the sender retries.
Scope of verification: The TypeScript code is verified with vitest unit tests (Web Bluetooth is replaced with a fake). The ESP32 sketch has been compiled with arduino-cli. Communication between a real browser and a real ESP32 is unverified. The full sample is in examples/bluetooth on GitHub.
1. The premise: browsers cannot connect to each other over Bluetooth
1-1. Why a browser cannot be a BLE peripheral
In BLE, the side that announces itself (advertises) is the Peripheral, and the side that discovers it and initiates the connection is the Central. To connect two devices directly, one of them has to wait as a Peripheral.
The Web Bluetooth specification, however, scopes itself to "a UA (browser) operating in the Central role connecting to a GATT server", and its IDL has no API for starting advertising or for exposing a GATT server. A browser cannot be the side that waits, so two browsers cannot connect to each other. A native app can sometimes act as a Peripheral, but that capability is not available to web pages. So the waiting role goes to a separate device.
1-2. What Web Bluetooth does
Web Bluetooth is an API that lets a browser connect to a BLE device's GATT server, read and write characteristics (containers for values), and subscribe to notifications. As of 2026-11-17 the specification is a W3C Community Group draft (last updated 2026-06-03), not a W3C Recommendation. Chrome supports it without a flag on Android, ChromeOS, macOS and Windows; Linux requires a flag. Firefox and Safari do not support it, and Mozilla and WebKit have both publicly taken negative positions on standardizing it.
The connection basics (filters for requestDevice(), serializing GATT operations, reconnecting after a disconnect) are covered in the Web Bluetooth API implementation guide. This article reuses the connection manager class BleConnection built there as-is and focuses on the chat layer on top of it.
1-3. The topology: PC A → ESP32 → PC B
The browsers on PC A and PC B both connect to the ESP32 as Centrals. The ESP32 is a Peripheral that exposes a GATT service for the chat. A frame written by PC A is sent to PC B by the ESP32 as a notification, and the reverse direction works the same way. There is no direct radio link between PC A and PC B.
PC A (Chrome) ESP32 PC B (Chrome)
Central ── write ──▶ Peripheral ── notify ──▶ Central
◀─ notify ── (GATT relay) ◀── write ──
PC A ✕ PC B : no direct Bluetooth connection
The ESP32 is more than a pass-through. It performs a minimal set of checks: it rewrites the sender number, discards malformed frames, and refuses to send a frame larger than the recipient can accept. Background such as which Bluetooth layer does what, and whether HTTP or TCP can run over BLE, is in the series pillar, Bluetooth vs Wi-Fi.
1-4. Separate "how the HTML arrives" from "how messages travel"
You cannot say "a Bluetooth chat needs no internet" unconditionally. There are two paths to consider separately.
The first is how the chat UI (HTML and JavaScript) reaches the browser. Web Bluetooth is only available in a secure context; a page served over http:// has no navigator.bluetooth. Roughly, a secure context is a page served over https:// or from an origin that points at your own machine, such as localhost (the Secure Contexts spec treats 127.0.0.0/8 and ::1 as "potentially trustworthy", and treats the name localhost the same way under certain conditions). Serving over https means the first load needs a network; serving from localhost means someone has to set that up.
The second is the path chat messages take. Once the page is open, messages travel only over BLE and never pass through a server.
Installing the core and libraries for the ESP32 also normally uses a network. The sample has no mechanism for opening the page offline (such as a Service Worker), and none has been tested. The accurate statement is: once setup is done and the page has loaded, exchanging messages does not use the internet.
I can take on the implementation from this article as an engagement
Connecting BLE and Wi-Fi devices to a web app — from choosing the approach to planning the prototype
2. Making the ESP32 a relay peripheral
2-1. Versions, and why the sketch does not mix in the built-in BLE library
| Item | This sample | Verified facts |
|---|---|---|
| Arduino core | esp32:esp32 3.3.12 | Latest stable release, published 2026-09-18. 4.0.0-RC1 is a pre-release |
| BLE library | NimBLE-Arduino 2.5.2 | Published 2026-10-25. Listed in the Arduino Library Manager index |
| Board | ESP32 Dev Module (esp32:esp32:esp32) | — |
According to its README, the BLE library bundled with the core uses Bluedroid on the original ESP32 in the 3.3 series and is planned to move entirely to NimBLE in 4.0.0. NimBLE-Arduino is a separate library with its own NimBLE host. The header names do not collide, but there are several recorded fixes for build errors and crashes that occurred when it was combined with a core that embeds NimBLE. So, as the author's own judgment call, the sketch does not mix the two, and the versions are pinned.
2-2. Accepting multiple Centrals: the default of 3, and resuming advertising
In NimBLE-Arduino's configuration file nimconfig.h, the simultaneous-connection limit CONFIG_BT_NIMBLE_MAX_CONNECTIONS defaults to 3, with a comment saying "the ESP32 controller supports at most 9". The sample assumes the default of 3.
The other trap is advertising. The Link Layer chapter of the Core Specification says a Peripheral that receives a connection request leaves the advertising state ("shall exit the Advertising state"). NimBLE-Arduino does not resume advertising after a successful connection, and in 2.x it does not resume automatically after a disconnect either (per the migration guide). To accept a second device and beyond, you have to restart it yourself.
class ServerCallbacks : public NimBLEServerCallbacks {
void onConnect(NimBLEServer* s, NimBLEConnInfo& info) override {
Serial.printf("connect handle=%u peers=%u\n", info.getConnHandle(), s->getConnectedCount());
// Advertising stops when a Central connects; resume it so more can join.
if (s->getConnectedCount() < kMaxCentrals) NimBLEDevice::startAdvertising();
if (kRequireEncryption) NimBLEDevice::startSecurity(info.getConnHandle());
}
void onDisconnect(NimBLEServer* s, NimBLEConnInfo& info, int reason) override {
removeSubscriber(info.getConnHandle());
Serial.printf("disconnect handle=%u reason=0x%x\n", info.getConnHandle(), reason);
}
When the third device connects, advertising is not resumed; once someone disconnects, advertiseOnDisconnect(true) restarts it. The last line requests pairing when encryption is required (section 10). On the browser side, the device picker (the chooser) appears every time the page is opened, because getDevices(), which returns previously chosen devices, is still behind a flag.
3. GATT layout: one service, RX and TX
3-1. UUIDs: random 128-bit values, in lowercase
GATT identifies services and characteristics by UUID. The sample uses these three.
| Name | UUID | Direction | Property |
|---|---|---|---|
| Chat service | cb777dd5-3ca7-4b0d-a487-252e8aa82b34 | — | Primary service |
| RX | 97b860da-5ced-41b3-be51-d4684a734d26 | Browser → ESP32 | Write (with response) |
| TX | c242c325-07bb-4a81-aa61-d9e644f1dd5b | ESP32 → browser | Notify |
RX and TX are named from the ESP32's point of view (the same convention as the Nordic UART Service). Write the UUIDs in lowercase: under the Web Bluetooth spec, a string that is not a lowercase 128-bit UUID throws a TypeError. And because reusing the Nordic UART Service UUIDs would make the device indistinguishable from a genuine NUS device, use random values you generate yourself. For a product, regenerate the values in this sample too.
The browser-side entry point follows. BleConnection takes care of subscribing to notifications, serializing writes, and reconnecting on disconnect.
// ...
// Call this from a click handler: requestDevice() needs a user gesture.
export async function startChat(callbacks: ChatCallbacks): Promise<ChatHandle> {
const bluetooth = getBluetooth();
if (!bluetooth) throw new Error("Web Bluetooth is not available in this browser");
const device = await bluetooth.requestDevice({
filters: [{ services: [CHAT_SERVICE_UUID] }],
});
const session = new ChatSession({
write: (frame) => connection.write(frame),
onMessage: callbacks.onMessage,
onStatus: callbacks.onStatus,
onDiagnostic: callbacks.onDiagnostic,
});
const connection = new BleConnection(device, {
service: CHAT_SERVICE_UUID,
notifyCharacteristic: CHAT_TX_UUID,
writeCharacteristic: CHAT_RX_UUID,
onNotification: (value) =>
session.receive(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)),
onStateChange: callbacks.onConnectionState,
});
await connection.connect();
return {
session,
close: async () => {
session.dispose();
await connection.disconnect();
},
};
}
The connection that session refers to is created on the next statement, but that is fine: write is only called after the connection is established.
3-2. Write (with response) vs. Notification
Of the ATT (Attribute Protocol) operations that carry values, four matter for this sample.
| Operation | Direction | Response | Use in this sample |
|---|---|---|---|
Write Request (writeValueWithResponse) | Client → server | Write Response returned | Writes to RX |
Write Command (writeValueWithoutResponse) | Client → server | None | Not used |
| Notification | Server → client | None | Delivery from TX |
| Indication | Server → client | Confirmation returned | Not used |
The ATT chapter of the Core Specification defines the Write Response as confirming that "the attribute has been successfully written". RX uses writes with response so that the browser-side Promise means "the ESP32 received it". Writes without response are faster, but in the shipped API the behavior when you pass more than ATT_MTU − 3 bytes is not defined, and the author has not been able to confirm what happens.
TX uses Notification. With Indication, a server cannot send the next Indication to a peer until that peer returns a Confirmation, so every peer costs a round trip per message. Worse, the Confirmation comes from the peer's Bluetooth stack and says nothing about whether the page finished reassembling the message. So delivery uses Notification, and "did the other app receive it?" is answered by the application-layer ACK in section 7.
4. ATT_MTU, payload size and UTF-8
4-1. 23 − 3 = 20, minus a 9-byte header leaves 11 bytes of payload
The size of the value that fits in one write or notification is set by the ATT_MTU. Per the GATT specification, the default ATT_MTU for LE is 23 bytes. ATT writes and notifications spend 3 of those bytes on the opcode (1 byte) and the attribute handle (2 bytes), leaving ATT_MTU − 3 bytes for the value.
Default ATT_MTU 23 → value 20 → payload 20 − 9 = 11
Negotiated ATT_MTU 247 → value 244 → payload 244 − 9 = 235
(bytes; value = ATT_MTU − 3, payload = value − 9 header;
247 is one example of a negotiated MTU)
"BLE is limited to 20 bytes" is a misconception. 20 bytes is merely the size that gets through even to a peer that has not negotiated the MTU. The MTU can be negotiated after connecting, and becomes the smaller of the two sides' receive limits. An attribute value can be at most 512 bytes, and 247 is just one value you often see after negotiation.
4-2. Web Bluetooth does not tell you the MTU
Per the spec, the browser negotiates the MTU when it connects, but as of 2026-11-17 no API that reports the result to the page has shipped. Issue #383, which asks for an API to get the MTU, has been open since 2018, and PR #672, which adds maxWriteWithoutResponseSize, is still at the proposal stage.
So the sample uses 20 bytes, which always gets through, as its default frame size. The ESP32 asks for a larger MTU with NimBLEDevice::setMTU(247), but since the browser cannot see the outcome, the sample favors reliability over speed.
export const PROTOCOL_VERSION = 1;
export const HEADER_BYTES = 9;
// ATT_MTU is at least 23 bytes and an ATT write or notification spends 3 of
// them on opcode + handle. 20 bytes is therefore the size that every peer is
// guaranteed to accept, not the maximum BLE can carry.
export const MIN_ATT_MTU = 23;
export const ATT_HEADER_BYTES = 3;
export const SAFE_FRAME_BYTES = MIN_ATT_MTU - ATT_HEADER_BYTES;
4-3. The relay never truncates
The ATT specification says that when an attribute value is longer than ATT_MTU − 3, a notification can carry only its first ATT_MTU − 3 bytes. If the relay forwarded a large frame as-is, the recipient could receive a frame with its tail cut off.
So the relay does not send a frame larger than the recipient's MTU − 3, rather than truncating it. The sender never gets an ACK and concludes "failed" when its timeout expires. That is easier to deal with than corrupted data arriving silently. As long as frames are sent at the default 20 bytes, this branch is never taken.
5. Frame format and splitting UTF-8
5-1. Byte layout
A frame consists of a 9-byte header followed by the payload. The table below gives the role of each byte. Multi-byte numbers are big-endian.
| Byte | Field | Size | Contents |
|---|---|---|---|
| 0 | version | 1 | Protocol version. Currently 1 |
| 1 | type | 1 | 0x01 is DATA, 0x02 is ACK |
| 2 | sender | 1 | Clients write 0; the relay overwrites it with the link's label |
| 3–6 | messageId | 4 | A random 32-bit value per message |
| 7 | index | 1 | Chunk number, starting at 0 |
| 8 | total | 1 | Number of chunks (1–255) |
| 9– | payload | Variable | A slice of the UTF-8 bytes. Empty for an ACK |
Message IDs are random so that they are unlikely to collide with IDs from a previous session after the page is reopened. The label the relay writes can itself be 0, so the UI must not use a sender of 0 to mean "me" or "unknown". The chunk count is one byte, so a message is at most 255 frames.
5-2. A worked split: 「こんにちは、BLE」 breaks in the middle of 「ち」
The example message is the Japanese greeting 「こんにちは、BLE」 ("Hello, BLE"). In UTF-8, each hiragana character and the Japanese comma 「、」 take 3 bytes, while Latin letters take 1 byte. The five hiragana plus the comma are 18 bytes and BLE is 3 bytes, for 21 bytes in total. One frame carries 11 bytes of payload, so the message splits into two frames.
The diagram below shows the exact bytes checked by the sample's test (frame.test.ts), with the message ID fixed at 0x0a0b0c0d. Frame 1 is the 9-byte header followed by the 9 bytes of 「こ」「ん」「に」 and the first 2 bytes of 「ち」 (e3 81), 20 bytes in all. Frame 2 starts with the remaining byte of 「ち」 (a1), followed by 「は」, 「、」 and BLE, 19 bytes in all. The vertical bar marks the boundary between header and payload for illustration only; it is not part of the data.
「こんにちは、BLE」 = 21 bytes in UTF-8
こ e3 81 93 ん e3 82 93 に e3 81 ab ち e3 81 a1
は e3 81 af 、 e3 80 81 B 42 L 4c E 45
Frame 1 (20 bytes = header 9 + payload 11)
01 01 00 0a 0b 0c 0d 00 02 | e3 81 93 e3 82 93 e3 81 ab e3 81
Frame 2 (19 bytes = header 9 + payload 10)
01 01 00 0a 0b 0c 0d 01 02 | a1 e3 81 af e3 80 81 42 4c 45
The receiver collects every frame before decoding the UTF-8, so cutting in the middle of a character is harmless. Converting each frame to a string on its own would decode just e3 81 and produce garbled text.
// Splits on byte boundaries, not characters: a 3-byte UTF-8 character may
// straddle two frames. The receiver decodes only after reassembly, so the
// split is harmless.
export function splitMessage(
text: string,
messageId: number,
maxFrameBytes: number,
maxMessageBytes: number,
): Uint8Array<ArrayBuffer>[] {
const chunkBytes = maxFrameBytes - HEADER_BYTES;
if (chunkBytes < 1) throw new RangeError(`maxFrameBytes ${maxFrameBytes} leaves no payload`);
const utf8 = new TextEncoder().encode(text);
if (utf8.byteLength === 0) throw new RangeError("empty message");
if (utf8.byteLength > maxMessageBytes) {
throw new RangeError(`message is ${utf8.byteLength} bytes, limit ${maxMessageBytes}`);
}
const total = Math.ceil(utf8.byteLength / chunkBytes);
if (total > 255) throw new RangeError(`message needs ${total} frames, limit 255`);
const frames: Uint8Array<ArrayBuffer>[] = [];
for (let index = 0; index < total; index++) {
const payload = utf8.subarray(index * chunkBytes, (index + 1) * chunkBytes);
frames.push(encodeFrame({ type: FrameType.Data, sender: 0, messageId, index, total, payload }));
}
return frames;
}
On the receiving side, decodeFrame() treats the incoming bytes as untrusted input. It throws if the frame is shorter than the header, has a different version or an unknown type, has a chunk index greater than or equal to the chunk count, or is an ACK carrying a payload.
5-3. The relay stamps the sender ID
The sender ID in header byte 2 is never taken from the client. The ESP32 overwrites it with the handle of the connection the write arrived on (a number the BLE stack assigns to each connection).
static void relay(QueuedFrame& frame) {
// The sender byte comes from the link, not from the client: a peer cannot
// claim to be another peer by writing a different number here.
frame.data[2] = static_cast<uint8_t>(frame.from & 0xFF);
uint16_t peers[kPeerSlots];
size_t count;
portENTER_CRITICAL(&peersLock);
count = subscriberCount;
memcpy(peers, subscribers, count * sizeof(uint16_t));
portEXIT_CRITICAL(&peersLock);
for (size_t i = 0; i < count; i++) {
if (peers[i] == frame.from) continue;
NimBLEConnInfo peer = server->getPeerInfoByHandle(peers[i]);
// The peer may have disconnected since the snapshot.
if (peer.getConnHandle() != peers[i]) continue;
if (kRequireEncryption && !peer.isEncrypted()) {
skippedUnencrypted++;
continue;
}
uint16_t mtu = peer.getMTU();
// Never send a truncated frame; the sender's ACK timeout will notice.
if (mtu < 23 || frame.length > mtu - 3) {
droppedOversize++;
continue;
}
if (!txChar->notify(frame.data, frame.length, peers[i])) notifyFailures++;
}
}
Always pass the recipient's connection handle to notify(). In the NimBLE-Arduino 2.5.2 source, the value-taking notify(data, len) without a handle sends to every connected peer whether or not it subscribed (contrary to its comment, which says "all subscribers"). So the sketch keeps a table of handles that subscribed via onSubscribe and sends to each one individually, skipping the sender and any peer that disconnected after the table was copied.
All this prevents is "claiming the number of another currently connected participant". A connection handle is not an identity. Anyone in range who can connect can join, and a handle can change on reconnect or be reused by a different device. The sender byte is a label for "which link this came from"; if you use it as a name, the same person can look like someone else after reconnecting.
6. Reassembly, duplicate suppression and resource limits
On the receiving side, Reassembler collects in-progress frames under the key sender:messageId and decodes the UTF-8 once every chunk has arrived. The sender is part of the key so that fragments do not get mixed up if two people happen to pick the same ID.
A protocol with retries has to expect the same message to arrive twice. So the IDs of completed messages are remembered in a small LRU (a set that forgets the oldest entries first), and a repeated ID is classified as a "duplicate". The chat layer does not display duplicates; it only sends an ACK (section 7).
Checking duplicates by message ID alone is deliberate. After a reconnect, a retry can arrive under a different sender byte, and including the sender would display the message twice. The cost: if different participants happen to pick the same 32-bit random value within the most recent 64 messages, the later one is not displayed. The author judged that probability negligible.
That reasoning only covers accidental collisions, though. Message IDs are broadcast to everyone in plaintext, so a malicious participant can send a short message that reuses the ID of a message still being split and get it in first. The receiver then treats the genuine remaining frames as duplicates, does not display them, and even sends an ACK, so the real sender sees "delivered". Where participants cannot be trusted, duplicate detection has to be keyed on a signed (sender key, sequence number) pair.
The other essential point is that every buffer has a limit. Without limits, an attacker could exhaust memory simply by flooding frames that declare a large chunk count and never sending the rest. The default limits are:
- 1024 bytes and 128 chunks per message
- 16 in-progress messages in total, at most 4 from the same sender
- An in-progress message is discarded 10 seconds after its last frame arrived
- 64 entries in the duplicate-suppression memory
At 11 bytes of payload per frame, 1024 bytes takes 94 frames, within the 128-chunk limit. The retention window counts from the last frame so that a long message on a slow link is not cut off partway. How long it takes to send 94 frames depends on the connection interval and other factors, and the author has not measured it.
accept(frame: Frame): ReassemblyResult {
// Duplicates are detected by messageId alone. The relay stamps the sender
// from the connection handle, which can change when a peer reconnects, so
// a retry after a reconnect arrives under a new sender byte. A random
// 32-bit id makes an accidental clash within the window negligible; a
// deliberate one by another participant is not prevented (see the article).
if (this.completed.has(frame.messageId)) {
return { kind: "duplicate", sender: frame.sender, messageId: frame.messageId };
}
if (frame.total > this.limits.maxChunks) {
return { kind: "rejected", reason: `too many chunks: ${frame.total}` };
}
if (frame.payload.byteLength > this.limits.maxMessageBytes) {
return { kind: "rejected", reason: `message exceeds ${this.limits.maxMessageBytes} bytes` };
}
// A one-frame message never occupies a pending slot, so a peer that fills
// the slots cannot block short messages from everyone else.
if (frame.total === 1) return this.finish(frame, [frame.payload]);
this.sweep();
const key = `${frame.sender}:${frame.messageId}`;
let entry = this.pending.get(key);
if (!entry) {
const rejected = this.checkQuota(frame.sender);
if (rejected) return rejected;
entry = {
sender: frame.sender,
total: frame.total,
chunks: new Array<Uint8Array | undefined>(frame.total),
received: 0,
bytes: 0,
lastSeenAt: this.now(),
};
this.pending.set(key, entry);
}
// ...
entry.chunks[frame.index] = frame.payload;
entry.received += 1;
entry.lastSeenAt = this.now();
if (entry.received < entry.total) return { kind: "incomplete" };
this.pending.delete(key);
return this.finish(frame, entry.chunks);
}
The decoder is created with fatal: true, so invalid UTF-8 is rejected. Frames that arrive out of order still reassemble. The chat layer reports how many messages were discarded on expiry through the diagnostic event expired. Because the duplicate-suppression memory holds 64 entries, a retry of a message older than that is displayed again.
7. Acknowledgements (ACK), retries and timeouts
7-1. Why you need an ACK even though the link layer retransmits
The Link Layer chapter of the Core Specification requires link-layer acknowledgement and flow control on every ACL connection, and retransmission of unacknowledged PDUs. An application-layer ACK is still necessary, because the link-layer acknowledgement only covers the two ends of a single radio link. This design has two links, PC A → ESP32 and ESP32 → PC B, with the ESP32's queue and software in between.
When PC A's write succeeds, all it learns is that the ESP32 received the bytes. If the queue is full they are discarded; if PC B's MTU is too small they are never sent. The Web Bluetooth spec itself says that between a disconnect and resubscribing there is "an unavoidable risk that some notifications will be missed". The only way to know whether the other chat window reassembled the message is to have the other app reply. It is the same idea as TCP building delivery confirmation on top of unreliable IP (TCP vs UDP). The thinking on idempotency, ACKs and reconnection from the WebSocket vs SSE decision guide applies directly as well.
The defaults: the time to wait for an ACK, ackTimeoutMs, is 3000 milliseconds; the number of send attempts, maxAttempts, is 3; and the number of messages that can be in flight at once, maxInFlight, is 4.
7-2. State transitions of an outgoing message
An outgoing message has four states. send() puts it in sending; once every frame has been written it moves to awaiting-ack; when the ACK arrives it becomes delivered. If the ACK arrives before the writes finish, it goes straight from sending to delivered. If ackTimeoutMs passes without an ACK, the message returns to sending and every frame is resent if the attempt count is below the limit; otherwise it becomes failed. A failed write is handled the same way.
send()
│
▼
sending ─────── ACK ───────▶ delivered
│ ▲
│ writes done │
▼ │
awaiting-ack ── ACK ─────────────┘
│
│ ackTimeoutMs elapsed
│ (from sending if a write fails)
▼
attempt < maxAttempts ?
│ yes: back to sending, resend all frames
│ no
▼
failed
7-3. The send-and-ACK sequence
When PC A writes frame 1 with response, the ESP32's onWrite puts it in the queue and returns, and at that point PC A receives the Write Response. Stamping the sender number and notifying PC B happen later, when loop() takes the frame off the queue. Frame 2 goes the same way. When PC B has every frame, it reassembles and displays the message, then writes an ACK. The ESP32 notifies PC A of the ACK, and PC A marks the message delivered.
PC A ESP32 PC B
│ write F1 │ │
│───────────────▶│ enqueue │
│◀─ Write Resp ──│ │
│ │ notify F1 │
│ │──────────────────▶│
│ write F2 │ │
│───────────────▶│ enqueue │
│◀─ Write Resp ──│ │
│ │ notify F2 │
│ │──────────────────▶│
│ awaiting-ack │ reassemble, show │
│ │◀──── write ACK ───│
│ │── Write Resp ────▶│
│ │ notify ACK │
│◀───────────────│ │
│ delivered │ │
If the ACK is lost, PC A resends F1 and F2 after the timeout. On PC B every resent frame is a duplicate, so nothing is shown, and an ACK is sent only once, on the last frame. Without that ACK, PC A would keep retrying and end up showing failed.
const result = this.reassembler.accept(frame);
const expired = this.reassembler.takeExpiredCount();
if (expired > 0) this.options.onDiagnostic?.({ type: "expired", count: expired });
switch (result.kind) {
case "complete":
this.options.onMessage({
sender: result.sender,
messageId: result.messageId,
text: result.text,
});
this.sendAck(result.messageId);
break;
case "duplicate":
// Our earlier ACK was lost and the sender retried: ACK again, but do
// not show the message twice. Every frame of the retry is a duplicate,
// so ACK once, on the last frame, instead of once per frame.
if (frame.index === frame.total - 1) this.sendAck(result.messageId);
break;
case "rejected":
this.options.onDiagnostic?.({ type: "frame-rejected", reason: result.reason });
break;
case "incomplete":
break;
}
ACK writes bypass the queue of pending data sends, so that an ACK is not delayed past the other side's timeout while a long message is being sent. BleConnection still serializes the GATT operations.
// ACKs skip our data queue, so a long outgoing message cannot delay them
// past the other side's timeout. The transport (BleConnection's GattQueue)
// still runs one GATT operation at a time.
private sendAck(messageId: number): void {
if (this.disposed) return;
this.options.write(encodeAck(messageId)).catch(() =>
this.options.onDiagnostic?.({ type: "write-failed", messageId, attempt: 0 }),
);
}
The retry timer is armed when each attempt's writes finish, whether they succeeded or failed.
private transmit(messageId: number): void {
const entry = this.outgoing.get(messageId);
if (!entry) return;
entry.attempt += 1;
const attempt = entry.attempt;
this.options.onStatus?.(messageId, "sending");
this.enqueueWrite(async () => {
for (const frame of entry.frames) {
if (this.disposed) return;
await this.options.write(frame);
}
})
.then(
() => {
if (this.outgoing.has(messageId)) this.options.onStatus?.(messageId, "awaiting-ack");
},
() => this.options.onDiagnostic?.({ type: "write-failed", messageId, attempt }),
)
.finally(() => this.armAckTimer(messageId));
}
// A failed write is treated like a lost ACK: wait, then retry. That covers
// a short disconnect while BleConnection is reconnecting.
private armAckTimer(messageId: number): void {
const entry = this.outgoing.get(messageId);
if (!entry) return;
entry.timer = setTimeout(() => {
if (entry.attempt >= this.maxAttempts) {
this.settle(messageId, "failed");
return;
}
this.options.onDiagnostic?.({ type: "retry", messageId, attempt: entry.attempt + 1 });
this.transmit(messageId);
}, this.ackTimeoutMs);
}
7-4. What "delivered" actually means
This ACK design has limits that will always come up in a production review.
- With three or more participants, it means "at least one person received it". An ACK carries only the message ID, and the sender marks the message
deliveredon the first ACK. To show delivery to everyone, the ACK has to name the recipient and the sender has to track each participant. - ACKs can be forged. DATA frames go to everyone, so any participant can send an ACK for someone else's message ID.
- With nobody else connected, sending always fails. If you are the only one connected, no ACK ever comes.
8. Recovering from disconnects
BLE connections drop easily: distance, radio conditions and sleep all break them. Recovery is split across two layers.
- The connection layer (
BleConnection): when it detects an unintended disconnect, it reconnects with exponential backoff. By default it tries up to 5 times, with a random delay in[0, min(8000, 500 × 2^attempt)]milliseconds (full jitter). Each attempt is cut off withgatt.disconnect()afterconnectTimeoutMs(10000 milliseconds by default), so it never gets stuck inreconnecting. When a connection attempt fails, or when it gives up reconnecting, it closes the link before enteringfailed, so no half-open connection is left behind. The details are in the Web Bluetooth API implementation guide. - The message layer (
ChatSession): writes during reconnection fail immediately. Each failure counts as one attempt, and the message is resent after the timeout. If the reconnect finishes in time, the retry gets through.
Connection states: connect() enters connecting, which becomes connected on success or failed on failure. An unintended disconnect enters reconnecting, which returns to connected on success or becomes failed after 5 failures. disconnect() moves to disconnected from any state and does not reconnect automatically.
connect()
│
▼
connecting ── failure ───▶ failed
│ success ▲
▼ │ 5 failures
connected ◀─ success ───── reconnecting
│ ▲
└── unintended disconnect ─┘
disconnect() → disconnected, from any state
The timing of the two layers interacts and needs care. The message layer arms a 3000-millisecond timer each time an attempt's writes finish or fail, so during a reconnect (when writes fail immediately) a message becomes failed in about 9 seconds. The reconnect layer's maximum waits add up to 500 + 1000 + 2000 + 4000 + 8000 = 15500 milliseconds, and the cut-off timeouts can add up to 5 × 10000 = 50000 milliseconds more, so reaching failed can take up to about 65.5 seconds. In other words, if a reconnect takes longer than about 6 seconds, messages sent during it are marked failed. Both figures are back-of-the-envelope calculations, not measurements. Whether to show a "Resend" button or to raise maxAttempts and ackTimeoutMs depends on your requirements.
Retries that span a reconnect are not displayed twice, because duplicates are detected by message ID. "Who said this", however, may appear to be a different person, so production should use an identifier that survives reconnects (the identity address of a bonded device, or a participant ID). session.dispose(), which close() calls, stops retries, ignores any later frames, and makes send() throw.
9. Buffer limits and backpressure
The sample puts a limit everywhere and, when a limit is exceeded, refuses rather than buffering.
| Location | Limit | Behavior when exceeded |
|---|---|---|
Browser sends (maxInFlight) | 4 messages | send() throws BackpressureError |
| Browser GATT operations | One at a time, serialized | The next operation waits for the previous one |
| ESP32 receive queue | 16 frames | Discards and increments droppedQueueFull |
| ESP32 simultaneous connections | 3 devices | Does not resume advertising; accepts no new connections |
| Receiver in-progress messages | 16 total, 4 per sender, 10 seconds from the last frame | Rejects new messages and discards expired ones |
Because send() throws once 4 messages are in flight, the UI should disable the send button and wait for results.
// Throws BackpressureError instead of queueing without bound; the UI should
// disable the send button until a message settles.
send(text: string): number {
if (this.disposed) throw new Error("ChatSession is disposed");
if (this.outgoing.size >= this.maxInFlight) {
throw new BackpressureError(`${this.maxInFlight} messages are still in flight`);
}
let messageId = this.newMessageId();
while (this.outgoing.has(messageId)) messageId = this.newMessageId();
const frames = splitMessage(text, messageId, this.maxFrameBytes, this.limits.maxMessageBytes);
this.outgoing.set(messageId, { frames, attempt: 0 });
this.transmit(messageId);
return messageId;
}
The ESP32's write callback runs on the NimBLE host task (a FreeRTOS task), so doing the fan-out there would hold up BLE events for every other connection. Instead it enqueues the frame and returns immediately, and loop() does the delivery. If the queue is full, the frame is dropped. This is the author's design decision, not a NimBLE-Arduino rule.
class RxCallbacks : public NimBLECharacteristicCallbacks {
// Runs on the NimBLE host task: copy the bytes into the queue and return.
void onWrite(NimBLECharacteristic* chr, NimBLEConnInfo& info) override {
NimBLEAttValue value = chr->getValue();
if (value.size() < kHeaderBytes || value.size() > kMaxFrameBytes) {
droppedMalformed++;
return;
}
QueuedFrame frame;
frame.from = info.getConnHandle();
frame.length = value.size();
memcpy(frame.data, value.data(), value.size());
if (xQueueSend(frameQueue, &frame, 0) != pdTRUE) droppedQueueFull++;
}
};
Even when a frame is dropped because the queue is full, the Write Response is still returned, so the browser sees success. That is one more reason a successful write cannot be read as "delivered".
10. Authentication, authorization and encryption
10-1. The sample is unencrypted by default
NimBLE-Arduino 2.5.2's initialization sets these defaults: no bonding (no stored keys), no MITM (man-in-the-middle) protection, no LE Secure Connections (legacy pairing), and NoInputNoOutput IO capability. The sample defaults to kRequireEncryption = false. In this state, chat contents go over the air unencrypted.
10-2. When kRequireEncryption is enabled
Setting kRequireEncryption to true makes the sketch do the following.
setSecurityAuth(true, false, true)enables bonding and requests LE Secure Connections (MITM protection stays off).- Every connection is asked to pair with
startSecurity()(section 2). - RX gets
WRITE_ENC. The migration guide describes this property as "only writable if paired/bonded (encrypted)", and unencrypted writes are rejected by the BLE stack. - Every delivery skips peers whose link is not encrypted. Subscription often happens before pairing, so this is checked frame by frame.
NimBLEService* service = server->createService(kServiceUuid);
uint32_t rxProperties = NIMBLE_PROPERTY::WRITE;
if (kRequireEncryption) rxProperties |= NIMBLE_PROPERTY::WRITE_ENC;
NimBLECharacteristic* rx = service->createCharacteristic(kRxUuid, rxProperties);
rx->setCallbacks(new RxCallbacks());
txChar = service->createCharacteristic(kTxUuid, NIMBLE_PROPERTY::NOTIFY);
txChar->setCallbacks(new TxCallbacks());
The author confirmed that the sketch compiles with this setting (section 12). However, its behavior on real hardware is unverified, and what it protects is limited.
- LE Secure Connections is not enforced. This setting means "use SC if the peer supports it too"; a peer without it falls back to legacy pairing. The sample has no setting that rejects anything other than SC (unverified). NIST SP 800-121 Rev. 2 says LE legacy pairing, except OOB with a 128-bit temporary key, "should be considered broken": anyone who can capture the pairing exchange can derive the resulting long-term key.
- MITM is not prevented. This ESP32 has no screen to display a number and no means of input (it stays NoInputNoOutput). NIST notes that when IO constraints rule out other methods, pairing falls back to Just Works, which has no MITM protection and is the weakest method in LE.
- The browser may not complete pairing. The spec only says the browser MAY attempt bonding, and in Chrome's implementation status, on-demand pairing is marked only for Android and Mac. Other OSes may require pairing in advance (unconfirmed).
- It is not authorization, and the relay sees plaintext. Anyone who can pair gets an encrypted link. Link encryption is per hop, so inside the ESP32 the messages are plaintext.
10-3. A connection handle is not an identity
A connection handle is a number that distinguishes "which connection this came from right now"; it says nothing about "who". To decide authorization (who is allowed to join), you need to check the identity address of a bonded device against an allowlist, or use per-participant keys at the application layer.
A bonding-based allowlist only means something if pairing is refused outside an enrollment window. NimBLE-Arduino stores 3 bonds by default (CONFIG_BT_NIMBLE_MAX_BONDS), and the default callback (ble_store_util_status_rr) is code that deletes the oldest peer's record when the store overflows. A new pairing could push out an enrolled device (confirmed in the source, not on hardware).
11. Spoofing and trust boundaries: a threat model
The limits, organized by threat. "What the sample does" and "What it does not do" are facts read from the code; "Production mitigation" is the author's recommendation, and the mitigations are meant to be combined.
| Threat | Example | What the sample does | What it does not do | Production mitigation |
|---|---|---|---|---|
| Spoofing | Claiming another participant's number | The relay stamps the sender ID from the connection handle | Verify participant identity. Handle changes and reuse | Allowlist of bonded devices; application-layer signatures with per-participant keys |
| ACK forgery | Sending an ACK with someone else's message ID | Nothing | Verify the ACK's recipient and sender | Include the recipient in the ACK and sign it |
| Dedup poisoning | Sending first with someone else's message ID so the real one is treated as a duplicate | Nothing | Verify who owns the ID | Sign a per-sender sequence number and detect duplicates by (key, sequence number) |
| Tampering | Rewriting the payload at the relay or in transit | Format checks (version, type, chunk index) | Verify payload integrity | Application-layer authenticated encryption (AEAD) or signatures |
| Replay | Replaying recorded frames later | Duplicate suppression over the last 64 messages | Reject anything older | Sign a per-sender sequence number or timestamp and persist the sequence |
| Resource exhaustion | Frame floods; occupying reassembly or connection slots | Limits on reassembly (16 total, 4 per sender, one-frame messages use no slot), queue, sends and connections | Defend against a peer that reconnects to change its sender byte (the 16 total slots can fill); drop lingering connections | Disconnect anything not on the allowlist; per-device rate limits |
| Eavesdropping | Capturing the radio traffic to read the payload | Nothing by default (encryption is optional) | Encrypt by default, enforce SC, protect against MITM | Allow SC only; passkey or similar methods on devices with a display or input; application-layer end-to-end encryption |
| Fake relay | A fake ESP32 advertising the same service UUID | Nothing (it just searches by UUID) | Verify the relay is genuine | Give the relay a key and verify it with challenge-response; end-to-end encryption that does not trust the relay |
There are two trust boundaries: the radio segment, where anyone can attempt to eavesdrop or connect, and the ESP32 itself, which sees everything in plaintext and decides sender IDs and recipients. The sample is a worked example that assumes "the relay is honest". If you do not trust the relay, encryption and signing have to happen entirely inside the browsers.
12. Running it, and the tests
12-1. Steps to get it running
For the ESP32, here are the commands the author actually ran, covering installation through compilation.
arduino-cli config init
arduino-cli config add board_manager.additional_urls https://espressif.github.io/arduino-esp32/package_esp32_index.json
arduino-cli core update-index
arduino-cli core install esp32:esp32@3.3.12
arduino-cli lib install "NimBLE-Arduino@2.5.2"
arduino-cli compile --fqbn esp32:esp32:esp32 --warnings all ble_chat_relay
The author has not flashed a board (via the Arduino IDE or arduino-cli upload); that step is unverified.
The browser side is a set of TypeScript modules with no UI. Bundle them with any bundler, build a page that calls startChat() from a click handler, and serve it from localhost or over https. Serving the page and connecting from Chrome are also unverified.
12-2. vitest and FakeRelay
The vitest tests run on fakes that stand in for Web Bluetooth and the ESP32. FakeRelay reproduces only three of the sketch's rules (stamp the sender number, deliver to everyone except the sender, do not send frames larger than MTU − 3); it does not model the subscription table, the encryption check, or the queue limit. The main things the tests confirm:
- The bytes from section 5, and that reassembly works even when a character is split or frames arrive in reverse order
- When an ACK is lost, the sender retries, and the receiver displays the message once and sends the ACK once. The same holds when the retry arrives under a different sender byte
- With no ACK the message becomes
failed; after a brief link drop a retry gets through; a frame larger than the MTU is not delivered - The various limits, that one-frame messages use no slot, the retention window, the expired count, and
dispose()
Here is the output (run by the author on 2026-11-17 in their own environment).
npx vitest run examples/bluetooth/ble-chat
✓ examples/bluetooth/ble-chat/web/chat-session.test.ts (11 tests) 10ms
✓ examples/bluetooth/ble-chat/web/reassembler.test.ts (14 tests) 3ms
✓ examples/bluetooth/ble-chat/web/frame.test.ts (13 tests) 3ms
Test Files 3 passed (3)
Tests 38 passed (38)
Passing tests do not prove that a real browser and a real ESP32 can connect. Chrome's behavior, MTU negotiation and the radio are not reproduced.
12-3. Compiling for the ESP32, and the serial log
The sketch was compiled with arduino-cli 1.6.0, esp32:esp32 3.3.12 and NimBLE-Arduino 2.5.2 with all warnings enabled. With kRequireEncryption set to both false (the committed setting) and true, the exit code was 0 and there were no warnings from the sketch.
kRequireEncryption = false (the committed setting)
Sketch uses 587784 bytes (44%) of program storage space. Maximum is 1310720 bytes.
Global variables use 36012 bytes (10%) of dynamic memory, leaving 291668 bytes for local variables. Maximum is 327680 bytes.
kRequireEncryption = true (a temporarily edited copy)
Sketch uses 587888 bytes (44%) of program storage space. Maximum is 1310720 bytes.
Global variables use 36012 bytes (10%) of dynamic memory, leaving 291668 bytes for local variables. Maximum is 327680 bytes.
Only compilation was confirmed. Flashing, advertising, connecting from Chrome, MTU negotiation and relaying between multiple devices are all unverified.
On real hardware, the serial log (115200 bps) is your main clue. It prints connects, disconnects and MTU changes, and every 10 seconds the number of connections and the counts of dropped frames (queue, malformed, oversize, notifyFail, unencrypted). Message bodies are never logged. The browser's diagnostic events likewise carry only IDs, reasons and counts. To isolate problems without a browser in the loop, check how the GATT server looks from a general-purpose BLE scanner app such as nRF Connect.
12-4. How this teaching sample differs from production
This sample is teaching material. For production it lacks participant authentication and authorization, application-layer encryption and signatures, a sender ID that survives reconnects, recipient-addressed ACKs, history and resynchronization, browser support including iPhone, and testing on real hardware (range, congested radio environments, long-running operation, battery).
The sample does not store messages. If you keep history, use IndexedDB, decide on a retention period and a way to delete, and never store keys or passwords in plaintext. Storing history also raises a new question: resynchronizing after a reconnect.
13. Comparison with WebRTC, Wi-Fi Direct and native BLE apps
Here is how this compares, as far as the author could confirm, with other ways to send messages without a server.
| Aspect | Web Bluetooth + ESP32 relay (this article) | WebRTC data channel | Native BLE app |
|---|---|---|---|
| Transport | BLE (GATT) | IP network (SCTP over DTLS over UDP) | BLE |
| Extra hardware | ESP32 required | None | None, if the device can act as a Peripheral |
| Connection setup | The user picks a device | Signaling (exchanging connection details) over a separate channel | App installation and OS permissions |
| Use from a web page | Chromium-based browsers only. Firefox and Safari unsupported | Supported in Chrome, Firefox and Safari (MDN compatibility data) | Not applicable (it is an app) |
| Size per frame | 20 bytes by default (11 bytes of payload) | Not bound by BLE's ATT_MTU | Same constraints as BLE |
According to RFC 8825, WebRTC signaling is application-specific and is normally carried over TLS-protected web technologies. RFC 8831 specifies the data channel as SCTP over DTLS over UDP. As of 2026-11-17 the author has not been able to confirm a standard API for using Wi-Fi Direct from a web page, so it is left out of the table.
In the author's view, Web Bluetooth is a strong option when the device already speaks BLE and you want to drive it from a browser. If you need large payloads or Safari on iPhone, consider WebRTC or a native app first.
14. Criteria for adopting this in production
A checklist for deciding whether to use this in a product. The same items work for evaluating an outside vendor.
Environment
- Can you restrict users to Chromium-based browsers? Is it acceptable to exclude Safari on iPhone?
- On Windows, ChromeOS and Linux, can you ask users to pair in the OS beforehand?
- Have you decided how the page is served (https, or localhost on each device) and whether the first load can use a network?
Communication and reliability
- How many devices connect at once? Is the default of 3 enough, and if you raise it, have you tested on real hardware?
- Does "delivered" mean "at least one person" or "everyone"? How will you design the ACK?
- Have you settled the relationship between how long reconnects take and how long retries continue before giving up?
- Can you move the data volume you need over Web Bluetooth, where you cannot rely on the MTU?
Security
- How do you decide who may join (authorization)? Are you relying on connection handles?
- Can you avoid Just Works? NIST SP 800-121 Rev. 2 says Just Works should not be used in LE. If you avoid it, will you give the relay a display or an input method?
- Can you avoid being connectable all the time? NIST says discoverable and connectable states are prone to attack and should be kept to a minimum (this relay keeps advertising while fewer than 3 devices are connected).
- Do you trust the relay? If not, how will you distribute the keys for application-layer encryption and signatures?
- Do your logs and on-device storage avoid keeping conversation contents or secrets?
Verification
- Do you have a plan to test on real hardware for range, radio congestion, long-running operation, and disconnect/reconnect?
- Are the firmware and library versions pinned, and do you have a procedure for retesting after core updates (such as the move to NimBLE in 4.0)?
- If you use an outside vendor, can they explain what they have verified and what they have not?
15. Summary
- A browser can only be a Central, so an ESP32 acts as a Peripheral relay and carries traffic PC A → ESP32 → PC B. "No internet needed" holds only for messages, after setup and after the page has loaded.
- With the default ATT_MTU of 23, each write carries 20 bytes. Split the UTF-8 bytes into 11-byte chunks and turn them back into a string only once every chunk has arrived.
- A successful write only means "it reached the relay", so build ACKs, retries and duplicate suppression by message ID into the application layer.
- Put a limit on every buffer. The sender ID is not an identity; encryption is off by default; even when it is on, SC is not enforced; and Just Works has no MITM protection.
- The TypeScript is tested against fakes and the ESP32 sketch has been compiled; communication on real hardware is unverified.