{"id":11443,"library":"node-opcua","title":"node-opcua - Pure Node.js OPC UA SDK","description":"node-opcua is a comprehensive, pure JavaScript/TypeScript implementation of the OPC Unified Architecture (OPC UA) stack, designed for Node.js environments. It enables the creation of OPC UA clients, servers, and related tools, facilitating machine-to-machine (M2M) and Industrial IoT (IIoT) communication. The package is actively maintained, with frequent minor and patch releases, currently stable at version 2.169.0, focusing on performance, memory optimization, and OPC UA 1.05 compliance. Key differentiators include its full adherence to the OPC UA specification, a robust architecture for handling large information models, and enterprise-grade support and value-added extensions provided by Sterfive SAS, which also sponsors its long-term development. It supports modern Node.js versions (>=18) and ships with TypeScript types for improved developer experience.","status":"active","version":"2.169.0","language":"javascript","source_language":"en","source_url":"git://github.com/node-opcua/node-opcua","tags":["javascript","OPCUA","opcua","m2m","iot","opc ua","internet of things","typescript"],"install":[{"cmd":"npm install node-opcua","lang":"bash","label":"npm"},{"cmd":"yarn add node-opcua","lang":"bash","label":"yarn"},{"cmd":"pnpm add node-opcua","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required runtime environment. Minimum version is 18.","package":"node","optional":false}],"imports":[{"note":"While older versions might have supported CommonJS, modern node-opcua versions (especially >=2.168.0 due to migration to native JS patterns) strongly encourage and are optimized for ESM import syntax with TypeScript.","wrong":"const OPCUAClient = require('node-opcua').OPCUAClient;","symbol":"OPCUAClient","correct":"import { OPCUAClient } from 'node-opcua';"},{"note":"Use named import from the main package. CommonJS require is not the recommended approach for modern usage.","wrong":"const OPCUAServer = require('node-opcua').OPCUAServer;","symbol":"OPCUAServer","correct":"import { OPCUAServer } from 'node-opcua';"},{"note":"Core types and enums are exported directly from the main `node-opcua` package. Avoid importing from internal or `dist` paths as these are subject to change without notice.","wrong":"import { ClientSession } from 'node-opcua/dist/schemas';","symbol":"DataType, AttributeIds","correct":"import { DataType, AttributeIds } from 'node-opcua';"}],"quickstart":{"code":"import { OPCUAServer, OPCUAClient, MessageSecurityMode, SecurityPolicy, DataType, Variant, AttributeIds } from \"node-opcua\";\nimport { resolve } from \"path\";\n\n// --- Server Setup ---\nasync function startServer() {\n    // Ensure a 'certificates' directory exists in your project root\n    // For production, manage certificates securely (e.g., via GDS)\n    // This example uses anonymous authentication for simplicity.\n    const server = new OPCUAServer({\n        port: 4334,\n        resourcePath: \"/UA/MySampleServer\",\n        buildInfo: {\n            productName: \"MySampleServer\",\n            buildNumber: \"1234\",\n            buildDate: new Date()\n        },\n        serverInfo: {\n            applicationUri: \"urn:MySampleServer\",\n            productUri: \"urn:MySampleServer\",\n            applicationName: { text: \"MySampleServer\", locale: \"en\" }\n        },\n        securityModes: [MessageSecurityMode.None],\n        securityPolicies: [SecurityPolicy.None],\n        allowAnonymous: true,\n        // Certificate files are needed even with securityMode.None in many setups\n        // The toolkit generates default ones in C:\\Users\\user\\AppData\\Roaming\\node-opcua-default-nodejs\n        // if not provided, but explicitly setting them is good practice for production.\n        // For simplicity in this quickstart, we assume default generation or manual placement.\n    });\n\n    await server.start();\n    console.log(`Server started on port ${server.port}`);\n    console.log(`Server endpointUrl: ${server.endpointUrl}`);\n\n    server.engine.addressSpace?.getFolder(\"ObjectsFolder\")?.addVariable({\n        nodeId: \"ns=1;s=MyDynamicVariable\",\n        browseName: \"MyDynamicVariable\",\n        dataType: DataType.Int32,\n        value: {\n            get: () => new Variant({ dataType: DataType.Int32, value: Math.floor(Math.random() * 100) })\n        }\n    });\n\n    return server;\n}\n\n// --- Client Setup ---\nasync function startClient(endpointUrl: string) {\n    const client = OPCUAClient.create({\n        endpointUrl,\n        securityMode: MessageSecurityMode.None,\n        securityPolicy: SecurityPolicy.None,\n        connectionStrategy: {\n            maxRetry: 0, // No retries for quickstart simplicity\n            initialDelay: 100\n        }\n    });\n\n    try {\n        await client.connect(endpointUrl);\n        console.log(\"Client connected to server.\");\n\n        const session = await client.createSession();\n        console.log(\"Client session created.\");\n\n        // Browse the root folder\n        const browseResult = await session.browse(\"RootFolder\");\n        console.log(\"RootFolder children:\");\n        for (const reference of browseResult.references || []) {\n            console.log(`  - ${reference.browseName.toString()}`);\n        }\n\n        // Read the value of MyDynamicVariable\n        const readValue = await session.read({\n            nodeId: \"ns=1;s=MyDynamicVariable\",\n            attributeId: AttributeIds.Value\n        });\n        console.log(`Value of MyDynamicVariable: ${readValue.value?.value}`);\n\n        await session.close();\n        await client.disconnect();\n        console.log(\"Client disconnected.\");\n\n    } catch (err) {\n        console.error(\"Client error:\", err);\n    }\n}\n\n// --- Main Execution ---\n(async () => {\n    let server: OPCUAServer | null = null;\n    try {\n        server = await startServer();\n        // Give server a moment to fully initialize\n        await new Promise(resolve => setTimeout(resolve, 1000));\n        await startClient(server.endpointUrl!); // Use the server's dynamically assigned endpoint\n    } catch (error) {\n        console.error(\"Error during quickstart execution:\", error);\n    } finally {\n        if (server) {\n            console.log(\"Shutting down server...\");\n            await server.shutdown();\n            console.log(\"Server shut down.\");\n        }\n    }\n})();","lang":"typescript","description":"This example demonstrates how to set up a basic OPC UA server, expose a dynamically updating integer variable, and then connect to it with an OPC UA client to browse its address space and read the variable's value. It uses anonymous authentication and no message security for simplicity. For production use, secure communication with certificates and user authentication is highly recommended."},"warnings":[{"fix":"Upgrade your Node.js runtime environment to version 18 or newer. Consider using an LTS version for stability.","message":"Node.js engine requirement updated to >=18. Applications running on older Node.js versions will cease to function or exhibit instability with current node-opcua releases.","severity":"breaking","affected_versions":">=2.123.0"},{"fix":"Review your codebase for direct dependencies on `async` or `lodash` utilities implicitly provided by older `node-opcua` versions. Adapt code to use native JavaScript alternatives or explicitly import `async`/`lodash` if still needed.","message":"Core packages fully migrated from `async`/`lodash` to native modern JavaScript patterns. If you had relied on internal utilities exposed from these previously, your code may break. This also affects the `node-opcua-pki` package, which had public API changes.","severity":"breaking","affected_versions":">=2.168.0"},{"fix":"Consult the `node-opcua-pki` release notes for detailed API changes. Migrate certificate handling code to the new, more robust API, especially regarding trust list management and PFX files. The `TrustListClient.addCertificate` method now accepts full certificate chains.","message":"Significant changes to certificate management architecture and APIs, particularly in `node-opcua-pki` (v6.0.0+), include sanitization of public API and new certificate validation options. Existing certificate management code may require updates.","severity":"breaking","affected_versions":">=2.167.0"},{"fix":"For client applications, update the `securityPolicy` to `SecurityPolicy.Aes256_Sha256_RsaPss` or ensure it matches the server's configured policy. Server applications can explicitly define `securityPolicies` in the constructor to re-enable older policies if compatibility is required.","message":"Default security policies on the server have changed to `Aes256_Sha256_RsaPss` (OPC UA 1.05 compliant), removing `Basic128Rsa15` and `Basic256` from defaults. Clients connecting to servers with default configurations may need to adjust their security policy.","severity":"breaking","affected_versions":">=2.123.0"},{"fix":"If encountering issues with PKCS1 padding on newer Node.js versions, add `--security-revert=CVE-2023-46809` to your Node.js command line. Evaluate the security implications of this revert for your application.","message":"For Node.js versions newer than 18.11.1 or >20.11.1, enabling PKCS1 padding (reintroduced in v2.123.0) requires the `--security-revert=CVE-2023-46809` argument when running Node.js. This reverses a security fix and should be used with caution.","severity":"gotcha","affected_versions":">=2.123.0"},{"fix":"For advanced use cases, comprehensive support, or commercial extensions, consider applying for the NodeOPCUA Subscription at https://support.sterfive.com or contacting Sterfive SAS.","message":"Advanced documentation and technical support, as well as several value-added extensions (e.g., PubSub, WebProxy, GDS, React components), are provided exclusively to registered members of the NodeOPCUA Subscription or through dedicated Professional Services.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Carefully configure `advertisedEndpoints` in your server settings to reflect the externally accessible IP address and port. Refer to the official documentation for detailed guidance on Docker/NAT deployment scenarios.","message":"When deploying in environments using Docker, NAT, or reverse proxies, correctly configuring 'Advertised Endpoints' (introduced in v2.165.0) is crucial to ensure clients can discover and connect to the server with the correct network addresses. Misconfiguration can lead to `ECONNREFUSED` or `Bad_TcpEndpointUrlInvalid` errors.","severity":"gotcha","affected_versions":">=2.165.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Migrate your project or the specific file to use ES Module `import` syntax (`import { Name } from 'node-opcua';`). Ensure your `package.json` has `\"type\": \"module\"` if using `.js` files for ESM, or use `.mjs` extensions.","cause":"Attempting to use `require()` to import `node-opcua`, which is primarily an ES Module package, or the build output is configured as ESM.","error":"Error [ERR_REQUIRE_ESM]: require() of ES Module not supported"},{"fix":"For development, set `securityMode: MessageSecurityMode.None` and `securityPolicy: SecurityPolicy.None` (if applicable) or `allowAnonymous: true` on the server. For production, generate valid certificates from a trusted CA, ensure all certificates in the chain are in the respective trust lists, or utilize a Global Discovery Server (GDS) for certificate management.","cause":"The client or server is configured to validate certificates strictly, but it encountered a self-signed certificate that is not in its trusted certificate store, or the certificate chain cannot be verified.","error":"Error: self signed certificate in certificate chain"},{"fix":"Verify the OPC UA server is running and listening on the specified port. Double-check the client's `endpointUrl` for correctness. Ensure no firewall rules (local or network) are blocking TCP traffic on the server's port. For Docker/NAT, ensure advertised endpoints are correctly configured.","cause":"The OPC UA client failed to establish a network connection to the server. This typically means the server is not running, the endpoint URL (IP/port) is incorrect, or a firewall is blocking the connection.","error":"Error: connect ECONNREFUSED"},{"fix":"Delete the auto-generated certificate files (typically found in `C:\\Users\\user\\AppData\\Roaming\\node-opcua-default-nodejs` on Windows or `~/.config/node-opcua-default-nodejs` on Linux) and restart the server to regenerate them with the correct host information. For custom certificates, ensure the certificate's subject alternative names (SANs) or common name (CN) match the server's application URI and hostname.","cause":"The application URI or hostname configured in the server's settings does not match the information embedded in its generated certificate, leading to potential client rejection.","error":"[NODE-OPCUA-W06] server : server certificate doesn't match the Server settings"}],"ecosystem":"npm"}