Node.js / TypeScript · recipe

Set up OPC UA certificates in Node.js

node-opcua manages a PKI directory for you. Point it at a folder, set your ApplicationUri to match the certificate's SAN, and choose a security policy and mode. The first connection will still need an administrator to trust you on the server.

Stacknode-opcua
Version2.181.1

The code

const {
  OPCUAClient, MessageSecurityMode, SecurityPolicy,
  OPCUACertificateManager,
} = require("node-opcua");

(async () => {
  const certificateManager = new OPCUACertificateManager({
    rootFolder: "./pki",        // MUST be a persistent volume in a container
    automaticallyAcceptUnknownCertificate: false,
  });
  await certificateManager.initialize();

  const client = OPCUAClient.create({
    applicationUri: "urn:example:my-opcua-client",   // must match the SAN URI entry
    clientCertificateManager: certificateManager,
    securityMode: MessageSecurityMode.SignAndEncrypt,
    securityPolicy: SecurityPolicy.Basic256Sha256,
    endpointMustExist: false,
  });

  await client.connect("opc.tcp://milo.digitalpetri.com:62541/milo");
  const session = await client.createSession();
  console.log("secure session established");

  await session.close();
  await client.disconnect();
})();

What it prints

secure session established
# ./pki/own/certs/  holds the generated certificate
# ./pki/rejected/  is where unknown peers land until you trust them

Notes

  • The certificate manager generates a self-signed certificate on first run and stores it under rootFolder. That folder is your identity.
  • In a container, mount ./pki on a persistent volume. Otherwise every restart regenerates the certificate and every peer's trust list goes stale on every deploy.
  • Never ship automaticallyAcceptUnknownCertificate: true. It is a development convenience that removes the point of the security you configured.
  • Trust is mutual: move your certificate into the server's trusted store, and put the server's certificate in ./pki/trusted.

What breaks first

The connection works locally and fails in the container after every deploy BadCertificateUntrusted
Mount the pki folder on a persistent volume so the application instance certificate survives restarts.

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.

Free download
OPC UA Troubleshooting & Integration Checklist
The field-tested checklist engineers use to diagnose certificates, ports and namespace problems fast, plus a Python (asyncua) client template.
Get the free checklist →
Free, no course, no login