You want users to open a URL and connect straight from the browser to a heart rate monitor, a sensor, or your own IoT device. The Web Bluetooth API is one of the few ways to do that. Most tutorials, though, date from around 2016 to 2019 and use plain JavaScript. I could not find one that covers TypeScript typings, reconnection, conflicting GATT operations and current browser support in one place.
This is an implementation guide for frontend and Next.js / React developers, IoT app developers, and anyone who wants to connect their company's BLE device to a web service.
What you will learn
- What Web Bluetooth can and cannot do (Central only, no advertising, no way to read the MTU)
- Which browsers and operating systems support it as of 2026-11-17, and where the spec stands
- How to run a minimal demo, and how to write everything from requestDevice to notification subscriptions in type-safe TypeScript
- Detecting disconnects, reconnecting, serializing GATT operations, handling each error name, and cleaning up in React
- When to choose a native app, Web Serial, WebUSB or WebRTC instead of Web Bluetooth
The short answer: Web Bluetooth is an API that turns the browser into a BLE Central (GATT client). It is a strong option for line-of-business apps and internal tools whose users can run a Chromium-based browser. It does not work in Safari on iPhone, though, and the spec is not yet an official W3C standard. Whether you can choose your users' devices is what decides it.
About the code in this article: every TypeScript code block is copied verbatim from a file in the sample repository. The code is verified with vitest unit tests, but the Web Bluetooth parts are test fakes. Connecting from a real browser to a real device has not been verified. Section 16 describes exactly what was verified.
1. What is Web Bluetooth?
Web Bluetooth is an API that lets JavaScript on a web page find nearby Bluetooth devices, connect to them, and read and write data. The entry point is navigator.bluetooth, and every operation reports back through Promises and DOM events. Working with BLE devices used to require a native app. With Web Bluetooth you can ship a device settings screen or a data visualization behind a plain URL, with no app store review.
1-1. Central and Peripheral, GATT client and server
As the introduction of the spec puts it, a BLE Peripheral is the side that accepts connections, and a Central is the side that connects to a Peripheral. A separate pair of terms describes data: the side that exposes data is the GATT server, and the side that reads and writes it is the GATT client. GATT (Generic Attribute Profile) is the standard for how a device structures the table of data it exposes.
The Web Bluetooth spec defines the scope of its first version this way: "The first version of this specification allows web pages, running on a UA in the Central role, to connect to GATT Servers over either a BR/EDR or LE connection." Chrome's documentation says the same. In other words, the browser is always the side that connects, never the side that gets connected to. That is why two browsers cannot connect to each other directly over Bluetooth; a device acting as the GATT server has to sit between them. The BLE chat article that uses an ESP32 as the relay builds exactly that.
1-2. How the browser relates to the OS Bluetooth stack
The browser does not drive the radio itself. A call from a web page goes through the browser's Web Bluetooth implementation to the OS Bluetooth stack, and the OS talks to the peripheral through the controller (the radio chip).
This division of labor shapes the behavior developers see. The browser handles the chooser, permissions, the blocklist check and the write-size check (512 bytes). The OS handles pairing, ATT_MTU negotiation and connection sharing. The spec's steps for connect() say to "Use the Exchange MTU procedure to negotiate the largest supported MTU," so the MTU is negotiated by the UA (in practice, the OS stack), not by the page. Chrome's documentation also notes that calling device.gatt.disconnect() does not stop communication if another app is talking to the same device.
The diagram below shows this vertical relationship from top to bottom: the web page; the browser's Web Bluetooth implementation (chooser, permissions, blocklist, 512-byte check); the OS Bluetooth stack (pairing, MTU negotiation, connection sharing); the Bluetooth controller; and finally the peripheral acting as the GATT server.
Web page (JavaScript / TypeScript)
│ navigator.bluetooth (Promises and DOM events)
▼
Browser's Web Bluetooth implementation
- Device chooser and permissions
- Blocklist, 512-byte limit check
▼
OS Bluetooth stack
- Windows / macOS / ChromeOS / Android / BlueZ
- Pairing, ATT_MTU negotiation, connection sharing
▼
Bluetooth controller (radio chip)
│ 2.4 GHz
▼
Peripheral (GATT server)
Where GATT, ATT and the MTU sit in the Bluetooth stack is explained in detail in the pillar article, Bluetooth vs Wi-Fi.
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. What it can and cannot do
The table below covers what I could confirm from the spec and from Chrome's implementation.
| Capability | Supported? | Basis and notes |
|---|---|---|
| Connect to a GATT server as a Central | Yes | This is the scope of the spec |
| Read and write services and characteristics | Yes | readValue() / writeValueWithResponse() and so on |
| Subscribe to notifications (Notify / Indicate) | Yes | startNotifications() |
| Browser advertises / acts as a Peripheral | No | The IDL has no API for advertising |
| Read the negotiated ATT_MTU | No | Not in the shipping API (Section 14) |
| Profiles other than GATT (RFCOMM/SPP, audio, etc.) | No | The API only deals with GATT. The terms RFCOMM and L2CAP never appear in the spec |
Filter by serviceData | Not implemented in Chrome | It is in the spec's IDL, but Chromium's IDL has a TODO (crbug.com/707635) |
| Access the HID service | No | Excluded by the blocklist (0x1812) |
| Use from a Web Worker | No | Exposed=Window only |
Retrieve previously permitted devices (getDevices()) | Behind a flag in Chrome | So is watchAdvertisements() |
The spec's introduction says that "the GATT protocol can also run over BR/EDR transport," and connecting to a GATT server over BR/EDR is in scope. So the accurate statement is not "it cannot talk to Classic at all" but "it cannot handle anything other than GATT, such as SPP/RFCOMM." According to a comment in the blocklist, HID is excluded because "Direct access to HID devices like keyboards would let web pages become keyloggers." Firmware update services that do not verify signatures, and FIDO-related UUIDs, are excluded too.
3. Support and spec status as of 2026-11-17
3-1. Browsers and operating systems
I checked support against MDN's browser-compat-data (BCD, commit 3cb1804) and the implementation status document in the spec repository.
| Environment | Status |
|---|---|
| Chrome (Windows, macOS, ChromeOS) | Enabled by default. BCD records desktop Chrome as a "partial implementation" from Chrome 70 (56–69 on macOS only) |
| Chrome (Linux) | Disabled by default. You must enable chrome://flags/#enable-experimental-web-platform-features |
| Chrome (Android) | Since Chrome 56. Requires Android 6.0 or later |
| Microsoft Edge | Since version 79, per the implementation status document |
| Samsung Internet | Since v6.4, per the implementation status document |
| Android WebView | Not supported |
| Firefox | Not supported. Mozilla's position is negative |
| Safari (macOS, iOS) | Not supported. WebKit's position is oppose |
| WebKit-based browsers on iOS | Not supported, same as Safari |
According to the implementation status document, the minimum OS requirements are OS X Yosemite, Windows 10 version 1703, and on Linux, Kernel 3.19 and BlueZ 5.41 or later. Mozilla's position is negative: its rationale says the CG relies only on user consent, "which we believe is not sufficient protection," and that the blocklist model "is unsustainable and presents a significant risk to users and their devices." WebKit's issue #570 was closed as position: oppose (2025-12-02), citing privacy, security and device-independence concerns. Whether the alternative-engine iOS browsers permitted in Japan and the EU offer Web Bluetooth is unverified as of 2026-11-17. BCD marks the whole API as experimental.
3-2. Spec status
The Web Bluetooth spec is a W3C Community Group draft (Draft Community Group Report, last updated 3 June 2026). The top of the spec states plainly that it is "not a W3C Standard nor is it on the W3C Standards Track."
In August 2026, WHATWG set up a "Peripheral APIs" workstream (Peripheral here means device APIs in general, not the BLE Peripheral role) covering Bluetooth alongside Serial, USB, HID and NFC. The repository moved to whatwg/bluetooth, and the spec now lives at bluetooth.spec.whatwg.org. The published text, however, is still the CG draft dated 3 June, so calling it a "W3C Recommendation" or a "WHATWG Living Standard" is wrong.
4. Three prerequisites before you start
4-1. HTTPS or localhost only
In the spec's IDL, navigator.bluetooth carries the SecureContext attribute. On an http:// page the property itself is therefore undefined, and no exception is thrown.
Under the Secure Contexts spec's algorithm, besides https, any origin whose host is in 127.0.0.0/8 or is ::1 is unconditionally "potentially trustworthy." The name localhost gets the same treatment in browsers that follow the rule that it always resolves to loopback. That is why you can test on http://localhost:3000 during development. Conversely, opening http://192.168.x.x from a phone on the same LAN does not work. The practical conclusion: never touch navigator.bluetooth directly.
4-2. User gestures and the device chooser
requestDevice() can only be called right after something like a click, while transient user activation is still active. The spec says it throws SecurityError without activation. Chrome's message is "Must be handling a user gesture to show a permission request."
When the call succeeds, the browser shows a chooser, and the page receives only the one device the user picked. The list of nearby devices is never handed to the page. If the user closes the chooser, Chrome rejects with NotFoundError ("User cancelled the requestDevice() chooser.").
The key point is that only requestDevice() needs a user gesture. The spec's steps for connect() contain no activation check. This is the foundation the reconnection design rests on.
4-3. Permissions-Policy and iframes
Web Bluetooth is controlled by Permissions Policy. The token is bluetooth, and the default allowlist is ["self"]. It works on same-origin pages with no extra setup and is unavailable in cross-origin iframes. According to MDN, to allow it in a cross-origin iframe you list the allowed origin in a Permissions-Policy: bluetooth header and also add allow="bluetooth" to the iframe (BCD lists the bluetooth header directive from Chrome 104). On a page where it is disallowed, Chrome returns SecurityError and getAvailability() returns false. If your site sets security headers centrally, check that it is not blocking it everywhere with bluetooth=().
5. Get it running first: a minimal demo
Before getting into the mechanics, let's run a minimal demo that just shows your heart rate on screen. No framework. The HTML is a button, a status line and a reading line.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Web Bluetooth heart rate demo</title>
</head>
<body>
<main>
<button id="connect" type="button">Connect a heart rate sensor</button>
<p id="status" role="status">Not connected</p>
<p id="reading" aria-live="polite">–</p>
</main>
<!-- Replace with the bundle built from demo-main.ts -->
<script type="module" src="./demo-main.js"></script>
</body>
</html>
The page script takes the three elements and waits for a click.
// A framework-free page script: one button, one status line, one reading.
// The element types are structural so the module runs in tests without a DOM;
// real HTMLButtonElement / HTMLElement objects satisfy them.
import { BleConnection, type ConnectionState } from "./connection";
import { parseHeartRateMeasurement } from "./heart-rate";
import { pickHeartRateMonitor } from "./pick-device";
export interface DemoElements {
button: EventTarget & { disabled: boolean };
status: { textContent: string | null };
reading: { textContent: string | null };
}
const STATE_LABEL: Record<ConnectionState, string> = {
connecting: "Connecting…",
connected: "Connected",
reconnecting: "Reconnecting…",
disconnected: "Disconnected",
failed: "Connection failed",
};
export function mountHeartRateDemo({ button, status, reading }: DemoElements): () => Promise<void> {
let connection: BleConnection | undefined;
const onClick = async (): Promise<void> => {
// requestDevice() runs before any await, inside the click's activation.
const picking = pickHeartRateMonitor();
button.disabled = true;
const picked = await picking;
if (!picked.ok) {
status.textContent = `No device selected (${picked.reason})`;
button.disabled = false;
return;
}
await connection?.disconnect();
connection = new BleConnection(picked.device, {
service: "heart_rate",
notifyCharacteristic: "heart_rate_measurement",
onNotification: (value) => {
try {
reading.textContent = `${parseHeartRateMeasurement(value).bpm} bpm`;
} catch {
reading.textContent = "Unreadable measurement";
}
},
onStateChange: (state) => {
status.textContent = STATE_LABEL[state];
},
});
try {
await connection.connect();
} catch {
// Already shown through onStateChange("failed").
} finally {
button.disabled = false;
}
};
button.addEventListener("click", onClick);
return async () => {
button.removeEventListener("click", onClick);
await connection?.disconnect();
};
}
onClick calls pickHeartRateMonitor() before its first await, and only then disables the button. That ordering keeps requestDevice() running while the click's activation is still valid. The connection itself is handled by BleConnection (Sections 8–10), and each notification goes through the parser from Section 9 to display something like "72 bpm". The returned function is the cleanup: it removes the listener and closes the connection.
The entry file just finds the elements in the HTML and passes them in.
// Entry point for index.html. Bundle from this file with any bundler and
// serve the page from https:// or http://localhost (a secure context).
import { mountHeartRateDemo } from "./demo";
function element<T extends Element>(selector: string): T {
const found = document.querySelector<T>(selector);
if (!found) throw new Error(`Missing element ${selector}`);
return found;
}
mountHeartRateDemo({
button: element<HTMLButtonElement>("#connect"),
status: element<HTMLElement>("#status"),
reading: element<HTMLElement>("#reading"),
});
To run it:
- From
web-bluetooth/in the sample directory, copyindex.htmland the.tsfiles thatdemo-main.tsimports (demo.ts,connection.ts,heart-rate.ts,pick-device.ts,errors.ts,types.ts) - Bundle them into a single JavaScript file with your bundler of choice, using
demo-main.tsas the entry, and save it as thedemo-main.jsthat thescriptelement inindex.htmlpoints to - Serve the folder from a static server on
http://localhostand open it in Chrome - Click the button and pick a device that has the Heart Rate service in the chooser
If you do not have a heart rate monitor, Chrome's documentation recommends "BLE Peripheral Simulator," an Android app that simulates the Battery, Heart Rate and Health Thermometer services. If the connection fails, open about://bluetooth-internals in Chrome to inspect nearby devices and their services, characteristics and descriptors (also from that documentation). Note that I have not run this demo on real hardware either; verification stops at tests with fakes (3 tests).
6. GATT basics and UUIDs
A GATT server exposes data in three levels: Service (a group of related functions) → Characteristic (an item that holds a value) → Descriptor (supplementary information). On a heart rate monitor, Heart Rate Measurement (0x2A37) sits under the Heart Rate service (0x180D). The hierarchy and how it relates to ATT are covered in the pillar article.
With Web Bluetooth you never write the CCCD (Client Characteristic Configuration, 0x2902), which holds the subscription state, yourself. When you call startNotifications(), the UA sets the CCCD bits. The blocklist also makes 0x2902 write-protected, because "Writing to this would let a web page interfere with other pages' notifications and indications."
A 16-bit UUID expands to 128 bits by placing the 16-bit number into the top 32 bits of 00000000-0000-1000-8000-00805f9b34fb (the spec's canonicalUUID()).
16-bit: 0x180D
128-bit: 0000180d-0000-1000-8000-00805f9b34fb
^^^^^^^^ this part changes (the rest is fixed)
The API accepts a number (0x180d), a SIG-defined name alias ('heart_rate'), or a 128-bit string. Strings have a trap: the spec says "a valid UUID is lower-case and does not use the 16- or 32-bit abbreviations defined by the Bluetooth standard," and rejects anything else with TypeError. Pasting an uppercase UUID straight from a datasheet will not work, so define custom UUIDs once, as lowercase constants.
7. Start with the types: Web Bluetooth in TypeScript
7-1. lib.dom has no types for it
The lib.dom.d.ts that ships with TypeScript has no Web Bluetooth types (zero hits for BluetoothDevice with this repository's TypeScript 5.9.3). Either install DefinitelyTyped's @types/web-bluetooth (the latest is 0.0.22, published 2026-10-21) or declare just the parts you use. This sample does the latter.
// The subset of the Web Bluetooth API that these samples use.
// TypeScript's lib.dom.d.ts does not ship Web Bluetooth types, so we declare
// only what we call, as module exports. @types/web-bluetooth is the full
// alternative: it declares global types instead, and types
// navigator.bluetooth as always present, so keep the getBluetooth() guard.
export type BluetoothServiceUUID = number | string;
export type BluetoothCharacteristicUUID = number | string;
export interface BluetoothLEScanFilter {
services?: BluetoothServiceUUID[];
name?: string;
namePrefix?: string;
}
// The spec rejects filters together with acceptAllDevices, and an empty
// filters list. The never fields and the non-empty tuple turn both into
// compile errors.
export type RequestDeviceOptions =
| {
filters: [BluetoothLEScanFilter, ...BluetoothLEScanFilter[]];
acceptAllDevices?: never;
optionalServices?: BluetoothServiceUUID[];
}
| {
acceptAllDevices: true;
filters?: never;
optionalServices?: BluetoothServiceUUID[];
};
export interface BluetoothRemoteGATTCharacteristic extends EventTarget {
readonly uuid: string;
readonly value?: DataView;
readValue(): Promise<DataView>;
writeValueWithResponse(value: BufferSource): Promise<void>;
writeValueWithoutResponse(value: BufferSource): Promise<void>;
startNotifications(): Promise<BluetoothRemoteGATTCharacteristic>;
stopNotifications(): Promise<BluetoothRemoteGATTCharacteristic>;
}
export interface BluetoothRemoteGATTService {
readonly uuid: string;
getCharacteristic(
characteristic: BluetoothCharacteristicUUID,
): Promise<BluetoothRemoteGATTCharacteristic>;
}
export interface BluetoothRemoteGATTServer {
readonly connected: boolean;
connect(): Promise<BluetoothRemoteGATTServer>;
disconnect(): void;
getPrimaryService(service: BluetoothServiceUUID): Promise<BluetoothRemoteGATTService>;
}
export interface BluetoothDevice extends EventTarget {
readonly id: string;
readonly name?: string;
readonly gatt?: BluetoothRemoteGATTServer;
}
export interface Bluetooth {
getAvailability(): Promise<boolean>;
requestDevice(options: RequestDeviceOptions): Promise<BluetoothDevice>;
}
// Returns undefined during SSR, in Firefox and Safari, and on any page that
// is not a secure context. Never touch navigator.bluetooth directly.
export function getBluetooth(): Bluetooth | undefined {
if (typeof navigator === "undefined") return undefined;
return (navigator as Navigator & { bluetooth?: Bluetooth }).bluetooth;
}
Three things are worth pointing out.
1. There is no serviceData. It is in the spec, but Chrome does not implement it. Having it in the type would suggest that writing it has an effect, so it is left out. Add manufacturerData (Chrome 92 and later per BCD) or exclusionFilters (Chrome 114 and later per BCD) when you need them.
2. getBluetooth() returns Bluetooth | undefined. @types/web-bluetooth 0.0.22 declares interface Navigator { bluetooth: Bluetooth; }, typing navigator.bluetooth as always present. In reality it is undefined over http:// and in Firefox and Safari, so trusting that type crashes at runtime with a TypeError. Representing undefined in the type lets the compiler catch a missing "unsupported" branch.
3. Combinations the spec rejects cannot be written. In the spec, filters and acceptAllDevices are mutually exclusive, and options with neither, or with an empty filters, are invalid. If you pass both, Chrome throws a TypeError at runtime ("Either 'filters' should be present or 'acceptAllDevices' should be true, but not both."). A naive { filters } | { acceptAllDevices: true } lets the both-keys form through, because excess property checking does not treat a key that exists on any member of the union as "excess" (I confirmed this with TypeScript 5.9.3). So each branch marks the other's key as never, and filters is a non-empty tuple. The sample's types.test.ts pins "both," "neither" and "empty filters" as type errors with @ts-expect-error. The one case this type cannot catch is a filter with no contents, filters: [{}].
7-2. TypeScript 5.7+ and Uint8Array<ArrayBuffer>
The argument of write(), which we will see later, is Uint8Array<ArrayBuffer>. TypeScript 5.7 made TypedArrays generic, and a lib.d.ts change in 5.9 created cases where a TypedArray backed by ArrayBufferLike is not assignable to BufferSource. The release notes recommend spelling out Uint8Array<ArrayBuffer>. This notation requires TypeScript 5.7 or later.
8. From click to connection
8-1. The overall data flow
The user's click calls requestDevice(), which returns the chosen BluetoothDevice. This is the only step that needs a user gesture. Next, device.gatt.connect() connects, getPrimaryService() fetches the service, and getCharacteristic() fetches the characteristic. startNotifications() subscribes, and each characteristicvaluechanged event delivers a DataView. On a disconnect, a gattserverdisconnected event arrives; you wait and then redo everything from gatt.connect() onward.
[click]
└ requestDevice({ filters }) ← needs a user gesture
└ chooser → BluetoothDevice
└ device.gatt.connect()
└ getPrimaryService("heart_rate")
└ getCharacteristic(
"heart_rate_measurement")
├ addEventListener(
│ "characteristicvaluechanged")
└ startNotifications()
└ one DataView per event
[disconnect] gattserverdisconnected
└ wait (backoff) → redo from gatt.connect()
8-2. requestDevice and filters
// The click handler side. requestDevice() is the only call that needs a user
// gesture; everything after it (connect, reconnect) does not.
import { classifyBleError, type BleFailure } from "./errors";
import { getBluetooth, type BluetoothDevice } from "./types";
export type PickResult =
| { ok: true; device: BluetoothDevice }
| { ok: false; reason: BleFailure };
// Call this directly from onClick. Do not await slow work first: user
// activation is transient and can expire before requestDevice() runs.
export async function pickHeartRateMonitor(): Promise<PickResult> {
const bluetooth = getBluetooth();
if (!bluetooth) return { ok: false, reason: "unsupported" };
try {
const device = await bluetooth.requestDevice({
filters: [{ services: ["heart_rate"] }],
});
return { ok: true, device };
} catch (error) {
return { ok: false, reason: classifyBleError(error, "request") };
}
}
This function never throws; it returns the discriminated union PickResult. Branching on ok alone splits the code, at the type level, into a branch where device is guaranteed and a branch where reason is known. It also matters that nothing is awaited before requestDevice(): inserting a wait can let the activation expire and produce a SecurityError.
acceptAllDevices: true lists every nearby device, which is handy for exploration but gives users room to pick an unrelated device. In my judgment, production code should filter by service UUID or name prefix as a rule.
8-3. Forget optionalServices and you get SecurityError
After connecting, you can only access services listed in filters[].services or optionalServices (per MDN). Calling getPrimaryService() for a service not on that list makes Chrome reject with SecurityError ("Origin is not allowed to access the service. Tip: Add the service UUID to 'optionalServices' in requestDevice() options.").
If you also want the monitor's battery level, add optionalServices: ['battery_service']. There is no API for adding services mid-connection; adding one means calling requestDevice() again (with a user gesture). List every service you might need at selection time.
8-4. gatt.connect, getPrimaryService, getCharacteristic
Connecting and fetching services live in the BleConnection class. First, the types it exposes.
export type ConnectionState =
| "connecting"
| "connected"
| "reconnecting"
| "disconnected"
| "failed";
export interface RetryPolicy {
maxAttempts: number;
baseDelayMs: number;
maxDelayMs: number;
}
export interface BleConnectionOptions {
service: BluetoothServiceUUID;
notifyCharacteristic: BluetoothCharacteristicUUID;
writeCharacteristic?: BluetoothCharacteristicUUID;
onNotification: (value: DataView) => void;
onStateChange?: (state: ConnectionState, error?: unknown) => void;
retry?: RetryPolicy;
// gatt.connect() can wait forever if the device never advertises again.
connectTimeoutMs?: number;
}
const DEFAULT_CONNECT_TIMEOUT_MS = 10_000;
const DEFAULT_RETRY: RetryPolicy = { maxAttempts: 5, baseDelayMs: 500, maxDelayMs: 8_000 };
The state is a union of string literals because a boolean isConnected cannot tell "reconnecting" from "gave up," which is how UIs end up frozen on "Connecting…". connectTimeoutMs is explained in Section 10.
Next is the core that goes from connecting to subscribing (excerpt from the BleConnection class).
// Characteristic objects from a previous connection are stale after a
// reconnect, so the whole service lookup and subscription is redone, on a
// fresh queue so that an operation that never settled cannot wedge it.
private async openSession(token: number): Promise<void> {
const gatt = this.device.gatt;
if (!gatt) throw new Error("Device has no GATT server");
const queue = new GattQueue();
const current = () => {
if (token !== this.session) throw new Error("superseded by a newer attempt");
};
await gatt.connect();
current();
const service = await queue.run(() => gatt.getPrimaryService(this.options.service));
current();
const notifyChar = await queue.run(() =>
service.getCharacteristic(this.options.notifyCharacteristic),
);
const writeUuid = this.options.writeCharacteristic;
const writeChar =
writeUuid === undefined ? undefined : await queue.run(() => service.getCharacteristic(writeUuid));
current();
this.detachCharacteristics();
this.queue = queue;
notifyChar.addEventListener("characteristicvaluechanged", this.handleValue);
this.notifyChar = notifyChar;
this.writeChar = writeChar;
await queue.run(() => notifyChar.startNotifications());
current();
}
private detachCharacteristics(): void {
this.notifyChar?.removeEventListener("characteristicvaluechanged", this.handleValue);
this.notifyChar = undefined;
this.writeChar = undefined;
}
private readonly handleValue = (event: Event): void => {
const value = (event.target as BluetoothRemoteGATTCharacteristic).value;
if (value) this.options.onNotification(value);
};
gatt.connect() resolves immediately if already connected (the spec's steps say "if connected is true, resolve"), so the same call works for both the first connection and reconnects. Service discovery runs one step at a time through a GattQueue (Section 11) that is created fresh for each attempt. current() checks after every await that this attempt is still the latest one; it works together with the timeout in Section 10. The listener is registered before startNotifications() so that the first notification right after subscribing is not missed.
event.target as BluetoothRemoteGATTCharacteristic is the only type assertion in connection.ts. The listener is only ever registered on notifyChar, so the structure of the code guarantees that target is a characteristic.
9. Reading, writing and notifications
9-1. Parsing Heart Rate Measurement with DataView
A characteristic's value arrives as a DataView, whether from readValue() or from characteristic.value. You read it by specifying offsets and endianness yourself, so wrapping this in a typed parser is the quickest way to make the code safe.
The example is Heart Rate Measurement (0x2A37). As defined in the GATT Specification Supplement, the first byte holds flags. If bit0 is 0 the heart rate is a uint8; if 1, a uint16. bit1 says whether sensor contact was detected, and bit2 whether contact detection is supported. If bit3 is 1, an Energy Expended field (uint16) follows; if bit4 is 1, RR-Interval fields follow (uint16, in units of 1/1024 s, possibly several).
The diagram below shows this byte layout and the 8-byte example used in the tests. The example has flags 0x18 (bit3 and bit4 set), a heart rate of 80, Energy Expended of 258, and RR-Intervals of 1024 (1000 ms) and 512 (500 ms).
byte 0 Flags
bit0 heart rate format 0=uint8 / 1=uint16
bit1 sensor contact detected
bit2 contact detection supported
bit3 Energy Expended present
bit4 RR-Interval present
byte 1 heart rate uint8 (when bit0=0)
byte 1-2 heart rate uint16 LE (when bit0=1)
next 2 bytes Energy Expended uint16 LE (bit3=1)
rest, 2 each RR-Interval uint16 LE (bit4=1)
e.g. 18 50 | 02 01 | 00 04 | 00 02
flags=0x18 bpm=80 | 258 | 1024 | 512
// Parses the standard Heart Rate Measurement characteristic (0x2A37) of the
// Heart Rate Service (0x180D). Because the format is standardised, one parser
// works with any sensor that implements the service.
export type SensorContact = "unsupported" | "not-detected" | "detected";
export interface HeartRateMeasurement {
bpm: number;
sensorContact: SensorContact;
// Raw uint16 as sent. Check the unit in the Heart Rate Service spec
// before showing it to users.
energyExpended?: number;
rrIntervalsMs: number[];
}
const FLAG_HR_UINT16 = 0x01;
const FLAG_CONTACT_DETECTED = 0x02;
const FLAG_CONTACT_SUPPORTED = 0x04;
const FLAG_ENERGY_PRESENT = 0x08;
const FLAG_RR_PRESENT = 0x10;
export function parseHeartRateMeasurement(view: DataView): HeartRateMeasurement {
if (view.byteLength < 2) {
throw new RangeError(`Heart Rate Measurement too short: ${view.byteLength} bytes`);
}
const flags = view.getUint8(0);
let offset = 1;
// Multi-byte fields in GATT characteristics are little-endian.
const readUint16 = (): number => {
if (offset + 2 > view.byteLength) {
throw new RangeError(`Heart Rate Measurement truncated at byte ${offset}`);
}
const value = view.getUint16(offset, true);
offset += 2;
return value;
};
let bpm: number;
if (flags & FLAG_HR_UINT16) {
bpm = readUint16();
} else {
bpm = view.getUint8(offset);
offset += 1;
}
const sensorContact: SensorContact = !(flags & FLAG_CONTACT_SUPPORTED)
? "unsupported"
: flags & FLAG_CONTACT_DETECTED
? "detected"
: "not-detected";
const energyExpended = flags & FLAG_ENERGY_PRESENT ? readUint16() : undefined;
// RR-intervals are in units of 1/1024 s; a notification may carry several.
// A trailing odd byte makes the whole measurement invalid (RangeError).
const rrIntervalsMs: number[] = [];
if (flags & FLAG_RR_PRESENT) {
while (offset < view.byteLength) {
rrIntervalsMs.push(Math.round((readUint16() * 1000) / 1024));
}
}
return { bpm, sensorContact, energyExpended, rrIntervalsMs };
Four design points:
- Make endianness explicit. The
trueingetUint16(offset, true)selects little-endian. Leave it out and the value is read big-endian, so 300 bpm (bytes2C 01) turns into 11265. The spec's example also usesgetUint16(index, /*littleEndian=*/ true). - Never read out of range. Check the remaining bytes before reading, and if there are not enough, throw a
RangeErrorthat says at which byte the data was cut off. An odd byte left over after the RR-Intervals also invalidates the whole measurement. - Sensor contact has three states. "Not supported" and "not in contact" mean different things, so they are not squashed into a
boolean. - Do not assume the unit. The comment in the spec's example says "Meaning 750kJ.", but the unit row in the GATT Specification Supplement says only joule. The resolution has to be checked in the Heart Rate Service specification, which I have not verified as of 2026-11-17. So the parser returns the raw value.
9-2. writeValueWithResponse vs writeValueWithoutResponse
| Method | ATT procedure | Good for |
|---|---|---|
writeValueWithResponse() | Write Request. Waits for the peer's response | Writes where you need to know it arrived, such as changing a setting |
writeValueWithoutResponse() | Write Command. Does not wait for a response | Small, frequent data where the next write can make up for a lost one |
The older writeValue() is deprecated in the spec ("Deprecated. Use writeValueWithResponse() and writeValueWithoutResponse() instead.") and marked deprecated in BCD too. The code does not say which kind of write it performs, so do not use it in new code. BCD lists the two newer methods from Chrome 85. The sample's write() favors reliability and uses only writeValueWithResponse() (excerpt from the BleConnection class).
export class BleConnection {
private queue = new GattQueue();
private readonly retry: RetryPolicy;
private readonly connectTimeoutMs: number;
private notifyChar?: BluetoothRemoteGATTCharacteristic;
private writeChar?: BluetoothRemoteGATTCharacteristic;
private userClosed = false;
private busy = false;
private reconnecting = false;
// True only while a fully opened session is up. A link that drops before
// that (including our own timeout abort) is a failed connect, not a reason
// to auto-reconnect.
private established = false;
// Increments for every attempt and on disconnect(). An attempt that lost a
// timeout race keeps running in the background; the token stops it from
// touching state that now belongs to a newer attempt.
private session = 0;
constructor(
private readonly device: BluetoothDevice,
private readonly options: BleConnectionOptions,
) {
this.retry = options.retry ?? DEFAULT_RETRY;
this.connectTimeoutMs = options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
}
async connect(): Promise<void> {
if (this.busy) throw new Error("connect() is already in progress");
this.busy = true;
this.userClosed = false;
this.established = false;
// Adding the same listener twice is a no-op.
this.device.addEventListener("gattserverdisconnected", this.handleDisconnected);
this.setState("connecting");
try {
await this.openSessionWithTimeout();
this.established = true;
this.setState("connected");
} catch (error) {
// If disconnect() ran meanwhile it already cleaned up. Touching the
// device now could abort a newer connection to it (React StrictMode
// mounts, unmounts and mounts again on the same device).
if (this.userClosed) throw error;
// Otherwise leave no listener and no half-open link behind.
this.device.removeEventListener("gattserverdisconnected", this.handleDisconnected);
this.detachCharacteristics();
this.device.gatt?.disconnect();
this.setState("failed", error);
throw error;
} finally {
this.busy = false;
}
}
write(bytes: Uint8Array<ArrayBuffer>): Promise<void> {
const target = this.writeChar;
if (!target) return Promise.reject(new Error("Not connected"));
return this.queue.run(() => target.writeValueWithResponse(bytes));
}
// User-initiated close: stop listening and never auto-reconnect.
async disconnect(): Promise<void> {
this.userClosed = true;
this.established = false;
this.session += 1;
this.device.removeEventListener("gattserverdisconnected", this.handleDisconnected);
const notifyChar = this.notifyChar;
this.detachCharacteristics();
if (notifyChar && this.device.gatt?.connected) {
await this.queue.run(() => notifyChar.stopNotifications()).catch(() => undefined);
}
this.device.gatt?.disconnect();
this.setState("disconnected");
}
Here is what connect() does, step by step:
- Calling it again while a connect or reconnect is in progress rejects with "connect() is already in progress", so the same connection is never opened twice.
- On failure, if
disconnect()ran in the meantime, it leaves the device alone and just rethrows.disconnect()has already cleaned up, and callinggatt.disconnect()here could take down a newer connection to the same device as collateral damage (this happens under React StrictMode; see Section 13). - On any other failure, it removes the listener and closes the half-open link before reporting
failed.
write() captures the write target in target before queuing, so if the link drops while the write waits its turn, the failure still goes straight back to the caller. disconnect() sets userClosed, advances session to invalidate any attempt in flight, unsubscribes, and then disconnects.
How each platform handles a writeValueWithoutResponse() larger than ATT_MTU − 3 is unverified as of 2026-11-17. The spec and Chrome apply the 512-byte limit to both kinds of write, but since the MTU cannot be read today, the safe starting point for writes without response is "20 bytes or less per write."
9-3. startNotifications and characteristicvaluechanged
You start a subscription with startNotifications(), receive notifications as characteristicvaluechanged events, and read the value from the event target's value. The spec says: "All notifications become disabled when a device is disconnected. A site that wants to keep getting notifications after reconnecting needs to call startNotifications() again, and there is an unavoidable risk that some notifications will be missed." That is fine for data like heart rate, where only the latest value matters. Data you cannot afford to lose needs an application-layer mechanism that numbers messages and re-requests missing ranges. The sequence-number and acknowledgment design in the BLE chat article is a worked example.
10. Disconnects and reconnection
10-1. gattserverdisconnected
A BLE connection can drop at any time, for example when the device moves out of range or loses power. When it does, a gattserverdisconnected event fires on the BluetoothDevice. According to the spec and Chrome's documentation, it also fires when the page itself calls gatt.disconnect(). The event alone therefore cannot tell you whether the user disconnected or the link dropped on its own. The sample distinguishes the two with a userClosed flag and by removing the listener first in disconnect().
10-2. Reconnection strategy
Reconnection rests on three facts.
- No new user gesture is needed (see 4-2). Chrome's documentation even includes an "Automatic Reconnect" sample that reconnects with exponential backoff.
- Old objects are unusable. Chrome's documentation says GATT attributes become invalid on disconnect and must be fetched again on every reconnect. Using an old characteristic gives
InvalidStateError("GATT Characteristic no longer exists."). - Notifications must be resubscribed (see 9-3).
private readonly handleDisconnected = (): void => {
this.detachCharacteristics();
const wasEstablished = this.established;
this.established = false;
if (!wasEstablished || this.userClosed || this.reconnecting) return;
void this.reconnect();
};
// A device the user already picked can be reconnected with gatt.connect()
// without a new user gesture; only requestDevice() needs one.
private async reconnect(): Promise<void> {
this.reconnecting = true;
this.busy = true;
this.setState("reconnecting");
let lastError: unknown;
try {
for (let attempt = 0; attempt < this.retry.maxAttempts; attempt++) {
await sleep(backoffDelay(attempt, this.retry));
if (this.userClosed) return;
try {
await this.openSessionWithTimeout();
this.established = true;
this.setState("connected");
return;
} catch (error) {
if (this.userClosed) return;
lastError = error;
}
}
// Giving up: do not leave a half-open link behind.
this.detachCharacteristics();
this.device.gatt?.disconnect();
this.setState("failed", lastError);
} finally {
this.reconnecting = false;
this.busy = false;
}
}
private setState(state: ConnectionState, error?: unknown): void {
this.options.onStateChange?.(state, error);
}
}
When the disconnect event arrives, the listener is removed from the old characteristic. established is true only while a fully opened session is up; a link that drops before that counts as a failed connect and does not trigger an automatic reconnect. reconnect() repeats "wait, then try openSessionWithTimeout()" up to maxAttempts times, and the openSession() inside it redoes everything from service discovery to subscribing on every attempt, so all three facts are handled in one place. If the user disconnects during a wait or after a failed attempt, it exits. When it gives up, it closes the half-open link before reporting failed.
The delay comes from exponential backoff with full jitter.
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
// Full jitter: a random delay in [0, min(max, base * 2^attempt)] so that
// several tabs reconnecting to the same peripheral do not retry in lockstep.
export function backoffDelay(attempt: number, policy: RetryPolicy, random = Math.random): number {
const ceiling = Math.min(policy.maxDelayMs, policy.baseDelayMs * 2 ** attempt);
return Math.floor(random() * ceiling);
}
With the defaults (base 500 ms, cap 8,000 ms), the first attempt waits a random 0–499 ms and the fifth a random 0–7,999 ms. The randomness matters because if several tabs reconnect to the same device at once, their retries would otherwise line up and keep colliding.
10-3. Add a timeout in case connect() never returns
The spec's steps for connect() include a note: "These procedures can wait forever if a connectable advertisement isn’t received. The website should call disconnect() if it no longer wants to connect." disconnect() aborts a pending connect() with AbortError (Chrome's message is "The GATT connect attempt was cancelled."). In Chromium this cancellation sits behind a feature flag called kWebBluetoothCancelConnect, which is enabled by default on the main branch. Which stable release first enabled it is unverified.
Without a timeout, gatt.connect() never returns while the device stays powered off, and the state is stuck at reconnecting. So the sample races openSession() against a timer, both on the first connect and on every reconnect attempt (excerpt from the BleConnection class).
// gatt.disconnect() aborts a pending connect() with an AbortError, which is
// how a hung attempt is cancelled.
private async openSessionWithTimeout(): Promise<void> {
const token = ++this.session;
let timer: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<never>((_, reject) => {
timer = setTimeout(() => {
this.session += 1;
this.device.gatt?.disconnect();
reject(new DOMException(`connect timed out after ${this.connectTimeoutMs} ms`, "TimeoutError"));
}, this.connectTimeoutMs);
});
try {
await Promise.race([this.openSession(token), timeout]);
} finally {
clearTimeout(timer);
}
}
Once connectTimeoutMs (10,000 ms by default) elapses, it advances session, aborts the pending connect() with gatt.disconnect(), and rejects with a DOMException named TimeoutError. Promise.race does not stop the losing side, so the timed-out attempt keeps running in the background. Because session has moved on, that attempt throws at its next current() and cannot overwrite the new attempt's notifyChar or queue. And even though the timeout's gatt.disconnect() drops a link that was never established, established is false, so no automatic reconnect starts. The 10 seconds is a placeholder of mine; tune it to your device's advertising interval.
Reloading the page loses the BluetoothDevice itself. getDevices(), which would retrieve the earlier device, is still behind a flag in Chrome, so assume the user has to pick the device again after a reload.
11. Serialize GATT operations
If you fire reads, writes and subscriptions in parallel, Chrome may reject the overlapping operation with NetworkError ("GATT operation already in progress."). In the Chromium source, the macOS and Windows implementations work per characteristic and reject the next operation while a read or write is pending. Other operating systems are unverified. The spec also says that "for now sites need to serialize their use of this API and/or give the user a way to retry failed operations" (Issue #188), and Chrome's documentation warns that parallel reads and writes "may raise errors depending on the platform" and suggests manually queueing GATT operation requests. Neither provides the queue code, though.
// Chrome can reject a GATT operation that overlaps one still in flight, so
// every read, write and (un)subscribe goes through one promise chain.
export class GattQueue {
private tail: Promise<unknown> = Promise.resolve();
run<T>(operation: () => Promise<T>): Promise<T> {
const result = this.tail.then(operation);
this.tail = result.catch(() => undefined);
return result;
}
}
run() starts the next operation only after the previous one finishes, and returns that operation's own result. The crux is this.tail = result.catch(() => undefined): if result became tail as-is, a single failure would leave the whole chain rejected and every later operation would fail. The failure is still returned as result, so nothing is swallowed. The sample creates a new queue for each connection attempt, so an operation that stalls without ever settling cannot block the next connection.
12. Error handling: classify by name and by call phase
Web Bluetooth rejections are almost always DOMExceptions, but the same name means different things depending on which call threw it. The sample therefore classifies by the pair of name and "phase" (request or gatt).
// Maps Web Bluetooth rejections to cases the UI can act on. The same
// DOMException name means different things depending on the call that threw:
// NotFoundError from requestDevice() is usually "the user closed the chooser",
// while NotFoundError from getPrimaryService() means the service is missing.
export type BleFailure =
| "unsupported"
| "chooser-closed"
| "not-allowed"
| "not-found"
| "operation-unsupported"
| "gatt-failed"
| "stale-handle"
| "value-too-large"
| "timeout"
| "aborted"
| "invalid-argument"
| "unknown";
export type BlePhase = "request" | "gatt";
export function classifyBleError(error: unknown, phase: BlePhase): BleFailure {
// For example an uppercase UUID string, or filters with acceptAllDevices.
if (error instanceof TypeError) return "invalid-argument";
if (!(error instanceof DOMException)) return "unknown";
switch (error.name) {
case "NotFoundError":
// In Chrome, requestDevice() also uses it for "Bluetooth adapter not
// available." Only the message text tells the two apart, and
// getAvailability() cannot detect a powered-off adapter, so word the UI
// as "no device was selected" rather than "you cancelled".
return phase === "request" ? "chooser-closed" : "not-found";
case "SecurityError":
// No user gesture, a blocklisted UUID, a service missing from
// optionalServices, or a Permissions-Policy block.
return "not-allowed";
case "NotSupportedError":
// The characteristic does not support the operation (for example,
// notify on a read-only value). Chrome reports an unsupported platform
// as NotFoundError instead; "unsupported" comes from getBluetooth().
return "operation-unsupported";
case "NetworkError":
// Disconnected, "GATT operation already in progress." (a missing
// queue), or "Not paired." Retry only after reconnecting.
return "gatt-failed";
case "InvalidStateError":
return "stale-handle";
case "InvalidModificationError":
return "value-too-large";
// BleConnection's own connect timeout.
case "TimeoutError":
return "timeout";
// gatt.disconnect() cancelled a pending connect().
case "AbortError":
return "aborted";
default:
return "unknown";
}
}
TypeError (bad arguments) is split off first, and anything else that is not a DOMException returns unknown rather than guessing. Because the return type is a union, the compiler can check that a switch in the UI is exhaustive. The table below maps the main failures to the names and messages found in the Chrome source and to the sample's classification.
| Situation | Call | Name and Chrome message | Class | UI response |
|---|---|---|---|---|
| Chooser closed | requestDevice | NotFoundError "User cancelled the requestDevice() chooser." | chooser-closed | "No device was selected" |
| No adapter | requestDevice | NotFoundError "Bluetooth adapter not available." | chooser-closed | Same, plus a prompt to check Bluetooth |
| Called outside a click | requestDevice | SecurityError "Must be handling a user gesture to show a permission request." | not-allowed | Fix the code to call it from a button |
| Not in optionalServices | getPrimaryService | SecurityError "Origin is not allowed to access the service. …" | not-allowed | Fix the code |
| Blocked by policy | Any call | SecurityError "Access to the feature "bluetooth" is disallowed by permissions policy." | not-allowed | Fix headers and iframe settings |
| Bad arguments | requestDevice etc. | TypeError (uppercase UUID, filters together with acceptAllDevices) | invalid-argument | Fix the code |
| Operation not permitted | Read, write, subscribe | NotSupportedError "GATT operation not permitted." | operation-unsupported | Check the characteristic's properties |
| Operation while disconnected | Any GATT call | NetworkError "GATT Server is disconnected. Cannot …" | gatt-failed | Wait for reconnection |
| Conflicting operations | Any GATT call | NetworkError "GATT operation already in progress." | gatt-failed | Route through the queue |
| Stale object | Any GATT call | InvalidStateError "GATT Characteristic no longer exists." | stale-handle | Fetch it again |
| Over 512 bytes | Write | InvalidModificationError "Value can't exceed 512 bytes." | value-too-large | Split the data |
| Connect aborted | gatt.connect | AbortError "The GATT connect attempt was cancelled." | aborted | Usually the result of your own disconnect |
| Connect timeout | BleConnection | TimeoutError (thrown by the sample itself) | timeout | Check the device's power and distance |
| Encryption required | Read, write | SecurityError "GATT operation not authorized." or NetworkError "GATT Error: Not paired." | not-allowed / gatt-failed | Guide the user to pair in the OS |
SecurityError maps to not-allowed regardless of phase because every one of its causes is fixed in the code or the deployment configuration, not by the user. NotSupportedError always maps to operation-unsupported. In the Chrome source, an unsupported platform is reported as NotFoundError ("Web Bluetooth is not supported on this platform…"), and unsupported means only that navigator.bluetooth is absent. A NotFoundError in the request phase cannot distinguish a cancellation from a missing adapter, and the spec says getAvailability() reports whether a radio is available "regardless of whether it is powered on or not," so the UI uses the neutral wording "No device was selected." Messages are implementation-specific, so log them but never branch on them.
13. Using it from React: lifecycle and cleanup
There are two principles. Pick the device in a click handler, and let an effect own the connection and always close it when it is no longer needed.
// React binding. The device is chosen in a click handler (user gesture) and
// passed in; the effect owns the connection and tears it down on unmount or
// when a different device is selected.
import { useEffect, useState } from "react";
import { BleConnection, type ConnectionState } from "./connection";
import { parseHeartRateMeasurement, type HeartRateMeasurement } from "./heart-rate";
import type { BluetoothDevice } from "./types";
export interface HeartRateState {
connection: ConnectionState | "idle";
latest: HeartRateMeasurement | null;
error: unknown;
}
export function useHeartRate(device: BluetoothDevice | null): HeartRateState {
const [state, setState] = useState<HeartRateState>({
connection: "idle",
latest: null,
error: null,
});
useEffect(() => {
if (!device) return;
// A torn-down connection can still report (its aborted connect() fails
// after cleanup, and StrictMode runs setup twice). Ignore it.
let active = true;
const connection = new BleConnection(device, {
service: "heart_rate",
notifyCharacteristic: "heart_rate_measurement",
onNotification: (value) => {
if (!active) return;
try {
const latest = parseHeartRateMeasurement(value);
setState((prev) => ({ ...prev, latest }));
} catch (error) {
// One malformed notification must not take the page down.
setState((prev) => ({ ...prev, error }));
}
},
onStateChange: (connectionState, error) => {
if (!active) return;
setState((prev) => ({ ...prev, connection: connectionState, error: error ?? null }));
},
});
connection.connect().catch(() => {
// Already reported through onStateChange("failed", error).
});
return () => {
active = false;
void connection.disconnect();
// Do not carry the old device's reading over to the next one.
setState({ connection: "idle", latest: null, error: null });
};
}, [device]);
return state;
}
In the component, call pickHeartRateMonitor() from the button's onClick, and when ok is true, put device into state and pass it to useHeartRate(device). Never call requestDevice() from an effect. An effect that runs on mount has no user gesture behind it, so it fails with SecurityError. Changing state in a click and then calling it from an effect is not reliable either, because it depends on how long the activation stays valid.
The dependency array is [device], so the old connection's disconnect() runs whenever the device changes and on unmount. The cleanup also resets the state to idle, so the previous device's reading never carries over to the next one.
In development, React's StrictMode runs one extra "setup → cleanup" cycle for every effect. During that cycle the first connection's connect() is aborted by disconnect() and fails a little later, but two mechanisms protect the second connection. The per-effect active flag discards callbacks from a torn-down connection. And BleConnection.connect() does not touch the device on failure once disconnect() has run, so it does not take down the second connection to the same device. I verified the BleConnection side of this behavior with tests against fakes, but the hook itself has no tests and has not been checked in a real browser. How Chrome behaves when an abort and a reconnect overlap on the same device is unverified on real hardware.
14. Constraints that bite in production
14-1. 512 bytes per value, and assume you do not know the MTU
The Core Specification's ATT (Vol 3 Part F) caps an attribute value at 512 octets. The Web Bluetooth spec checks this on write and says to reject with InvalidModificationError when it is exceeded, and Chrome returns the same error with "Value can't exceed 512 bytes." Note that it is not NetworkError.
How large a value fits in one write or notification is set by ATT_MTU. The default ATT_MTU on LE is 23, and a Write Request or notification value can be at most ATT_MTU − 3.
Value limit = ATT_MTU − 3 (opcode 1 + handle 2)
Default (no negotiation): 23 − 3 = 20 bytes
Negotiated example: 247 − 3 = 244 bytes
(247 is a common value, not a spec constant)
"BLE maxes out at 20 bytes" is wrong; 20 is the value at the default ATT_MTU. Web Bluetooth, however, ships no API that lets the page read the negotiated result, and issue #383 asking for one has been open since 2018. Spec PR #672, which adds BluetoothRemoteGATTServer.maxWriteWithoutResponseSize, is still open; chromestatus lists it as "Proposed" (target milestone 160), and BCD has no entry for it. It is enabled by default on Chromium's main branch, but its status in stable releases is unverified. Once it ships, the safe approach is to use it behind feature detection and keep chunking for environments that lack it.
So for data larger than 20 bytes, design application-layer chunking and reassembly (framing) on the assumption that you do not know the MTU. Frame design and implementation are covered in the BLE chat article.
14-2. Pairing is up to the OS, and on-demand pairing works on only some of them
A characteristic that requires encryption needs pairing (bonding, if the keys are stored). The spec says only that "the UA MAY attempt to bond," and the page has no way to control it. According to a note in the spec, this is because macOS's Core Bluetooth does not provide that control. In the implementation status table, only Android and Mac are marked for "On-demand device pairing." On Windows, ChromeOS and Linux, access to an encrypted characteristic may fail unless the device was paired in the OS settings first. I have not checked the actual behavior on Windows. If your product uses encryption, include per-OS pairing instructions in your user documentation.
14-3. Bound to the page's lifetime
Web Bluetooth is available only in Window contexts, not from Workers. Closing or reloading the page loses the BluetoothDevice; getDevices() and watchAdvertisements() are behind flags, and persistent permissions are behind chrome://flags/#enable-web-bluetooth-new-permissions-backend. Requirements like "keep measuring after the tab is closed" or "connect automatically when the page opens" cannot be met as of 2026-11-17.
15. When not to choose Web Bluetooth
The table below is a rough selection guide I built from the research for this article. Support information covers only what I confirmed in BCD and MDN.
| Situation / requirement | First choice | Why |
|---|---|---|
| The device is a BLE GATT server, and users are on desktop Chrome / Edge (Linux needs a flag) or Android | Web Bluetooth | Distribute with just a URL. No app store review |
| Users include iPhone / iPad | A native app, or an architecture that goes over the network | Safari and WebKit-based browsers on iOS do not support it |
| Embedding screens in an Android app via WebView | The native BLE API | Android WebView does not support Web Bluetooth |
| You want the browser to be a Peripheral (to advertise) | A native app | Web Bluetooth is Central only |
| Keep the connection after the tab closes, or connect automatically on launch | A native app | No Workers, and getDevices() is behind a flag |
| The device is a USB serial device (CDC-ACM) or a Bluetooth SPP virtual serial port | Web Serial | The device appears as a serial port, not as GATT |
| The device is a custom USB device with no class driver | WebUSB | An API for exposing custom USB devices to the web |
| Real-time communication between browsers or with remote devices | WebRTC or WebSocket (through a server) | Bluetooth is short-range, and browsers cannot connect to each other directly |
- Web Serial: according to MDN, it handles serial ports as well as devices that emulate a serial port over USB or Bluetooth (USB CDC-ACM or Bluetooth SPP). BCD lists full support from Chrome 89, and from 148 in Chrome for Android. Firefox supports it on desktop from 151, but according to MDN's release notes the user has to install a site-specific permission add-on. Safari does not support it.
- WebUSB: MDN explains that devices in standard classes are handled by the OS's class drivers, and WebUSB is the API for devices that do not fit any class. BCD lists it from Chrome 61. Firefox and Safari do not support it, and BCD marks the whole API as experimental.
Remote real-time communication is built on an IP network. Through a server, WebSocket and SSE are the candidates; how to choose between them is laid out in the WebSocket vs SSE architecture decision guide. To get data from a BLE device to a remote location, a realistic architecture splits short and long range across different technologies: "device → Web Bluetooth page → WebSocket to the server."
In my judgment, Web Bluetooth shines most in "business and internal uses where you can specify the users' devices." If you can standardize field tablets on Android, or your company PCs all run Chrome, not having to build a native app is a big advantage. For a consumer product where you cannot leave out iPhone users, starting from a native app will save rework.
16. How this code was verified
The TypeScript in this article is reproduced from files in examples/bluetooth/web-bluetooth/, and a test mechanically checks that every code block in the article matches a contiguous run of lines in the source (translated comment lines are excluded from the comparison). The unit tests use vitest, with Web Bluetooth replaced by fakes. The fakes are stricter than Chrome: they reject overlapping operations per device with "GATT operation already in progress.", and return new characteristic objects on every service lookup to reproduce old objects becoming unusable after a reconnect.
- Connecting, subscribing, serialized writes, reconnecting and resubscribing after a disconnect, and cleanup after the attempts run out
- Timing out a
connect()that never returns, rejecting a second concurrentconnect(), and overlapping connections to the same device as in StrictMode - Heart Rate Measurement parsing, error classification, the
RequestDeviceOptionstypes (@ts-expect-error), and the demo from click to display
Here is the output (2026-11-17, run in my environment).
npx vitest run examples/bluetooth/web-bluetooth
RUN v4.1.4 /Users/tomodahinata/ProgrammingCode/products/portfolio
✓ examples/bluetooth/web-bluetooth/connection.test.ts (16 tests) 11ms
✓ examples/bluetooth/web-bluetooth/demo.test.ts (3 tests) 4ms
✓ examples/bluetooth/web-bluetooth/pick-device.test.ts (3 tests) 3ms
✓ examples/bluetooth/web-bluetooth/heart-rate.test.ts (5 tests) 2ms
✓ examples/bluetooth/web-bluetooth/errors.test.ts (6 tests) 2ms
✓ examples/bluetooth/web-bluetooth/types.test.ts (1 test) 1ms
Test Files 6 passed (6)
Tests 34 passed (34)
Start at 09:01:12
Duration 509ms (transform 45ms, setup 0ms, import 80ms, tests 22ms, environment 0ms)
Passing tests are not evidence that a real browser can connect to a real device. They do not reproduce the chooser, OS pairing, radio conditions or platform differences. Connecting from a real browser to real hardware, whether the 10-second timeout is appropriate, and how the React hook actually behaves are all unverified as of 2026-11-17.
17. Summary: a pre-production checklist
- Confirmed your users' browsers and operating systems (Chromium-based only; Linux needs a flag; Safari, iOS, Firefox and Android WebView are out)
- Served over HTTPS, never touch
navigator.bluetoothdirectly, and wrote theundefinedbranch - Call
requestDevice()directly from the click handler, with noawaitbefore it - Listed every service you use in
filters[].servicesoroptionalServices - Defined custom UUIDs as lowercase 128-bit strings
- Use
writeValueWithResponse()/writeValueWithoutResponse()deliberately instead ofwriteValue() - Serialize GATT operations through a single queue
- Discard old objects on disconnect, and redo everything from service discovery to subscribing on reconnect
- Reconnect with full-jitter backoff, with a cap on attempts and a timeout on
connect() - Classify errors by name and phase, and do not word
chooser-closedin a way that blames the user - Keep each write at 512 bytes or less, and design framing on the assumption that the MTU is unknown
- If encryption is required, include per-OS pairing instructions in your user guidance
- In React, disconnect in the effect's cleanup and ignore state updates from torn-down connections
When the conditions fit, Web Bluetooth lets you build web apps that connect to BLE devices with nothing to install. Its constraints are just as clear: browser support, spec maturity, and the opacity of the MTU and pairing. Use the code and tables in this article as material for deciding whether to adopt it.