← Blog

HL7 v2 over MLLP in Node

An HL7 v2 feed on a TCP socket arrives one message at a time, each message wrapped in three framing bytes and answered with an acknowledgment. The wrapper is MLLP, the Minimal Lower Layer Protocol. This post builds a receiver for it in Node.js with two of our libraries: @cosyte/mllp for the socket and @cosyte/hl7 for the message. Code first.

npm install @cosyte/mllp @cosyte/hl7
import { createStarterClient, createStarterServer } from "@cosyte/mllp";
import { parseHL7 } from "@cosyte/hl7";

const committed: string[] = [];

// The receiver. Port 0 lets the OS pick a free port; the host defaults to 127.0.0.1.
const server = await createStarterServer({
  port: 0,
  onMessage: async (payload) => {
    const msg = parseHL7(payload.toString("latin1"));
    console.log(msg.meta.controlId, msg.warnings.map((w) => w.code));
    const mrn = msg.patient?.mrn;
    if (mrn === undefined) throw new Error("no patient identifier"); // the sender gets AE
    committed.push(`${msg.meta.type} ${mrn}`); // your durable write goes here
  },
});

// The sender, standing in for the upstream system.
const client = await createStarterClient({
  host: "127.0.0.1",
  port: server.getStats().port ?? 0,
});

// Two synthetic admits. The second one arrives without its PID segment.
const admit = (controlId: string, body: string) =>
  Buffer.from(
    `MSH|^~\\&|ADT|HOSP|LIS|HOSP|20261020090000||ADT^A01^ADT_A01|${controlId}|P|2.5\r` +
      "EVN|A01|20261020090000\r" +
      body,
  );

for (const message of [
  admit("MSG0001", "PID|1||MRN12345^^^HOSP^MR||ROE^SAM\rPV1|1|I\r"),
  admit("MSG0002", "PV1|1|I\r"),
]) {
  const ack = await client.send(message);
  const msa = ack
    .toString("latin1")
    .split("\r")
    .find((s) => s.startsWith("MSA|"))
    ?.split("|");
  const [, ackCode, controlId] = msa ?? []; // MSA-1 and MSA-2
  console.log(ackCode, controlId); // the acknowledgment code and the control ID it answers
}
console.log(committed.length); // what was stored holds a record number, so log a count

await client.close();
await server.close();

It prints:

MSG0001 []
AA MSG0001
MSG0002 [ 'MISSING_EXPECTED_GROUP' ]
AE MSG0002
1

The first admit is complete, so it parses with no warnings, the handler commits it, and the sender gets AA. The second is missing its PID segment. The parser still reads it and records what is wrong, the handler refuses it, and the sender gets AE with nothing committed. The acknowledgment’s own MSH-7 and MSH-10 change on every run, which is why the program prints only MSA-1 and MSA-2 from it. Nothing it prints names the patient: control IDs, warning codes, acknowledgment codes, and a count.

What MLLP puts on the wire

MLLP adds three bytes to a message and nothing else: a start block, 0x0B, in front, and an end block, 0x1C, followed by a carriage return, 0x0D, behind. HL7 v2 needs it because the standard does not define a network protocol of its own, and the IHE IT Infrastructure framework requires applications to use MLLP. You can look at a frame without opening a socket:

import { encodeFrame } from "@cosyte/mllp";

const frame = encodeFrame(
  Buffer.from("MSH|^~\\&|ADT|HOSP|LIS|HOSP|20261020090000||ADT^A01|MSG0001|P|2.5\r"),
);
console.log(frame[0] === 0x0b, frame.subarray(1, 4).toString() === "MSH");
console.log(frame.at(-3) === 0x0d, frame.at(-2) === 0x1c, frame.at(-1) === 0x0d);
true true
true true true

The first byte is the start block, 0x0B, and the message’s own MSH follows it. At the far end, 0x0D is the carriage return that closes the last HL7 segment, and 0x1C with a final 0x0D closes the frame. The two carriage returns do different jobs, and a reader has to tell them apart. FrameReader does the reverse of encodeFrame for bytes in whatever chunks TCP delivers them.

The acknowledgment comes after the commit

The acknowledgment code goes in MSA-1: AA for application accept, AE for application error, and AR for application reject. MSA-2 carries the control ID of the message being answered, which is how a sender matches each answer to the message it sent. A sender treats AA as permission to forget the message, so a receiver that answers before its own write has succeeded can lose a message without anyone noticing.

@cosyte/mllp makes the order structural. When the server has a handler, it awaits the handler and only then answers: AA if it resolves, AE if it throws, and AR if it throws an MllpAckError that asks for one. That is what happened to MSG0002 above. The text in MSA-3 comes from a fixed pair (“message could not be processed”, “message rejected”), so the error you throw, which may well name a patient, stays on your side of the socket.

One more case answers AE even when the handler resolves: an inbound message the sender could not match an AA to, such as one with an empty MSH-10 or a batch in a single frame. The message is still committed, and the server emits a nack event naming the reason, because a positive acknowledgment the sender cannot correlate is one it will resend.

MLLP with acknowledgments is at-least-once delivery at best, so a sender that times out will send the same message again. Keep your commit idempotent: the mllp README suggests de-duplicating on MSH-10 together with MSH-7.

Warnings you can log

msg.warnings is how the parser reports what it tolerated. A warning carries a stable code and a position rather than the value that caused it, so the handler above can log it as it is. In the message structure HL7 publishes for ADT_A01, PID is required, and MSG0002 has none, so it gets MISSING_EXPECTED_GROUP. The warning’s own text says what that usually means: the message may be truncated or misrouted. A receiver can route on the code without reading the message.

The transport side reads even less. @cosyte/mllp locates the MSH segment to build the acknowledgment and stops at that segment’s terminator, so on the transport path PID is never read, decoded, or echoed. The parse in the handler is yours, and so is anything you log from it.

What it does not do

  • Batch acknowledgment is not built. A batch envelope (FHS and BHS) or a frame carrying more than one MSH gets a warned AE rather than an AA for the first message alone.
  • MLLP Release 2 is not spoken.
  • Encryption is opt-in, because plain MLLP is cleartext on the wire. TLS is built on node:tls with certificate verification on by default, and the server binds 127.0.0.1 unless you allow a wildcard bind explicitly.

Where to go next

The MLLP page and the HL7 v2 page list each library’s limits and alternatives. The quickstarts for mllp and hl7 go further. If you would rather we build and run the interface itself, that is what integration services are for.

Sources

Read on October 7, 2026.