Server-side MQTT protocol codec and connection state machine for JavaScript and TypeScript runtimes. Accepts connections from MQTT clients, parses bytes into typed packets, encodes packets into bytes, and manages per-connection protocol state.
bun add @qualithm/mqtt-wire
# or
npm install @qualithm/mqtt-wire
import * as net from "node:net"
import { MqttWire, PacketType } from "@qualithm/mqtt-wire"
const server = net.createServer((socket) => {
const wire = new MqttWire({
onSend: (data) => {
socket.write(data)
},
onConnect: (connect) => {
console.log(`Client connected: ${connect.clientId}`)
return {
type: PacketType.CONNACK,
sessionPresent: false,
reasonCode: 0x00
}
},
onPublish: (packet) => {
const payload = new TextDecoder().decode(packet.payload)
console.log(`[${packet.topic}] ${payload}`)
},
onSubscribe: (packet) => ({
type: PacketType.SUBACK,
packetId: packet.packetId,
reasonCodes: packet.subscriptions.map((s) => s.options.qos)
}),
// The wire has ended the session (a client DISCONNECT, a protocol error or a
// hook that threw): close the socket too.
onDisconnect: () => socket.end()
})
// receive() resolves even when a hook throws; a rejection is a bug in the wire,
// so close the socket rather than let it go unhandled.
socket.on("data", (chunk: Buffer) => {
wire.receive(chunk).catch(() => socket.destroy())
})
socket.on("close", () => wire.reset())
})
server.listen(1883, () => console.log("MQTT server on port 1883"))
import {
BinaryReader,
BinaryWriter,
decodeVariableByteInteger,
encodeVariableByteIntegerToArray
} from "@qualithm/mqtt-wire"
// Encode a variable byte integer
const encoded = encodeVariableByteIntegerToArray(16384)
console.log(encoded) // Uint8Array [0x80, 0x80, 0x01]
// Decode it back
const decoded = decodeVariableByteInteger(encoded, 0)
if (decoded.ok) {
console.log(decoded.value.value) // 16384
}
// Build a packet manually
const writer = new BinaryWriter()
writer
.writeUint8(0x10) // CONNECT packet type
.writeVariableByteInteger(12) // Remaining length
.writeMqttString("MQTT") // Protocol name
.writeUint8(5) // Protocol version
const packet = writer.toUint8Array()
By default a QoS 1 PUBACK is sent before onPublish runs. Set pubackAfterDelivery to acknowledge
only once the hook resolves. A hook that throws ends the session with no PUBACK for that message, so
the client resends it when it reconnects. To refuse one message and keep the session, return a
PublishOutcome with a reasonCode of 0x80 or above instead of throwing.
const wire = new MqttWire(hooks, { pubackAfterDelivery: true })
onConnect, onPublish, onSubscribe and onUnsubscribe receive a second argument with a
signal. While the wire waits on a hook to answer (a CONNECT, a SUBSCRIBE, an UNSUBSCRIBE, or a QoS
1 PUBLISH under pubackAfterDelivery), the signal aborts when the session ends, however it ends.
Pass it to the hook's own I/O. Whatever a hook returns or throws after the signal aborts is
discarded, so no CONNACK or acknowledgement goes out for it. A delivery the wire doesn't wait on
(QoS 0, or a message already acknowledged) gets a signal that never aborts, since the client won't
resend it. The next session gets a fresh signal.
import { MqttWire, PacketType } from "@qualithm/mqtt-wire"
// lookUpDevice is your own data access; it takes the signal to cancel its request.
const wire = new MqttWire({
onConnect: async (connect, { signal }) => {
const device = await lookUpDevice(connect.clientId, { signal })
return { type: PacketType.CONNACK, sessionPresent: false, reasonCode: device ? 0x00 : 0x87 }
},
onSend: (data) => {
socket.write(data)
}
})
MqttWire uses lifecycle hooks for error reporting. receive() does not reject on protocol errors or
on a hook that throws: either one goes to onError and ends the session, with DISCONNECT on MQTT
5.0 (0x80 for a hook error) and a plain close on 3.1.1, and then onDisconnect runs with the error
as its second argument. Close the transport there.
When an error ends the session, the hooks run in this order: onSend with the DISCONNECT (MQTT 5.0
only), then onError, then onDisconnect. The wire waits up to closeTimeoutMs (5000 ms by
default) for that onSend, so a transport that never drains can't hold the session open. A throw
from onDisconnect goes to onError, and a throw from onError is dropped. An error that arrives
while the session is closing doesn't start a second close.
While a session ends, connectionState reads disconnecting: the wire sends its DISCONNECT and
nothing else. publish() rejects with a StateError, and acknowledgements for hooks still running
are dropped. The state is disconnected by the time onDisconnect runs.
onDisconnect runs exactly once per session, on every version and however the session ends: a
client DISCONNECT (passed as the first argument), a refused CONNECT, a protocol error or keepalive
timeout, a hook that threw (the error as the second argument), or your own disconnect() or
reset(). It runs after the last bytes the wire sends.
import {
decodeVariableByteInteger,
MqttWire,
ProtocolError,
StateError,
type DecodeResult,
type VarintDecodeValue
} from "@qualithm/mqtt-wire"
// Protocol errors from receive() are reported via the onError hook
const wire = new MqttWire({
onSend: (data) => {
socket.write(data)
},
onConnect: (connect) => ({
/* ... */
}),
onError: (error) => {
// A ProtocolError carries an MQTT reason code. Errors from decoding inbound
// bytes also carry a stable code: an oversized frame has code
// "PACKET_TOO_LARGE" and reason 0x95; other malformed input has 0x81.
if (error instanceof ProtocolError) {
console.error(`protocol error: ${error.message}`, {
reasonCode: error.reasonCode,
code: error.code
})
}
},
// Runs after the DISCONNECT is written, so ending the socket here doesn't drop it
onDisconnect: () => {
socket.end()
}
})
// receive() handles protocol and hook errors itself; a rejection is a bug in the wire
socket.on("data", (chunk: Buffer) => {
wire.receive(chunk).catch((err) => {
console.error("unexpected receive error", err)
socket.destroy()
})
})
// StateError is thrown by outbound methods when called in the wrong state
try {
await wire.publish("topic", payload)
} catch (error) {
if (error instanceof StateError) {
console.error(`state error: ${error.message}`, { state: error.state })
}
}
// Codec functions return Result types (no exceptions)
const result: DecodeResult<VarintDecodeValue> = decodeVariableByteInteger(data, 0)
if (result.ok) {
console.log(result.value.value)
} else {
console.error(`[${result.error.code}] ${result.error.message}`)
}
Full API documentation is generated with TypeDoc:
bun run docs
# Output in docs/
See the examples/ directory for runnable examples:
| Example | Description |
|---|---|
node-tcp.ts |
Node.js TCP server |
bun-tcp.ts |
Bun TCP server |
deno-tcp.ts |
Deno TCP server |
websocket.ts |
WebSocket server |
basic-usage.ts |
Low-level codec utilities |
batch-processing.ts |
Stream framing of chunked MQTT data |
error-handling.ts |
Result type patterns |
bun run examples/node-tcp.ts
mosquitto_pub / mosquitto_sub for conformance
tests (brew install mosquitto)bun install
bun run build
bun run test # unit tests
bun run test:coverage # with coverage report
bun run lint
bun run format
bun run typecheck
bun run bench
Apache-2.0