Node.js / TypeScript · recipe
Handle errors and reconnect in Node.js
Configure the built-in connectionStrategy and listen for the client's lifecycle events. node-opcua will re-establish the session and try to transfer subscriptions, but only if you let it manage the retry rather than reconnecting by hand.
| Stack | node-opcua |
|---|---|
| Version | 2.181.1 |
The code
const { OPCUAClient } = require("node-opcua");
(async () => {
const client = OPCUAClient.create({
endpointMustExist: false,
connectionStrategy: {
maxRetry: -1, // retry forever
initialDelay: 1000,
maxDelay: 30000, // cap the backoff
randomisationFactor: 0.5, // jitter: vital across a fleet
},
keepSessionAlive: true,
requestedSessionTimeout: 60000,
});
client.on("backoff", (retry, delay) =>
console.log(`retry ${retry}, next attempt in ${delay}ms`));
client.on("connection_lost", () => console.log("connection lost"));
client.on("connection_reestablished", () => console.log("reconnected"));
client.on("start_reconnection", () => console.log("reconnecting..."));
await client.connect("opc.tcp://opcua.umati.app:4840");
const session = await client.createSession();
session.on("session_closed", () => console.log("session closed"));
session.on("keepalive_failure", () => console.log("keepalive failed"));
console.log("running; the client now handles reconnection itself");
})();
What it prints
running; the client now handles reconnection itself
connection lost
reconnecting...
retry 1, next attempt in 1240ms
retry 2, next attempt in 2130ms
reconnected
Notes
- Set randomisationFactor. Without jitter, a fleet of collectors reconnects in lockstep after a network event and finishes the job the network event started.
- keepSessionAlive lets the client notice a dead session promptly instead of at the next read.
- Do not retry configuration errors. BadCertificateUntrusted and BadUserAccessDenied will fail identically forever: log once, alert, and stop.
- After reconnection, verify your monitored items are still reporting. A transferred subscription is the good case; a silently dead one is not.
- Classify before retrying: certificate and identity errors need a human, BadTooMany* means capacity, BadConnectionClosed is transient.
What breaks first
Two hundred collectors reconnect simultaneously and overwhelm the server
Add jitter with randomisationFactor and cap maxDelay. Staggering connects is the single most effective client-side measure against a connect storm.
BadTcpServerTooBusyAdd jitter with randomisationFactor and cap maxDelay. Staggering connects is the single most effective client-side measure against a connect storm.
Other recipes in this stack
Concepts on this page
Last verified 7 September 2026 against OPC UA 1.05.07. OPC UA Connect is an educational resource and is not affiliated with the OPC Foundation.