If you've ever built software for the EV (Electric Vehicle) charging industry, you know that the Open Charge Point Protocol (OCPP) is the undisputed standard for communication between Charge Points and Central Systems (CSMS).
But building a scalable, reliable, and secure OCPP-compliant system is notoriously difficult. Developers often struggle with guessing payload shapes, manually validating JSON schemas, implementing complex WebSocket framing, and handling connection drops.
That’s why I built ocpp-ws-io—a type-safe, production-ready OCPP WebSocket RPC client and server ecosystem for Node.js, built from the ground up with TypeScript.
🚀 Why another OCPP library?
Building a CSMS or a charge point simulator shouldn't require hand-writing validation logic or risking runtime errors from malformed payloads. ocpp-ws-io solves these problems by providing:
- 🎯 End-to-End Type Safety: Fully auto-generated TypeScript types covering all OCPP 1.6, 2.0.1, and 2.1 methods. No more guessing what a
BootNotificationpayload should look like. - 📐 Strict Schema Validation: Optional strict mode with built-in JSON schema validation before your business logic even touches the message.
- 🛜 Router built In: Router like express or huno built in for your modularity, clean code and easy use and manage.
- 🔒 Comprehensive Security: Out-of-the-box support for OCA Security Profiles 0–3 (Plain WS, Basic Auth, TLS + Basic Auth, and Mutual TLS).
- 🚦 DDoS Protection & Rate Limiting: Socket-layer Token Bucket Rate Limiting per station and method.
- 🔁 Resilience: Exponential backoff auto-reconnect, Redis state-synchronization, and Idempotency Keys to guarantee exactly-once message delivery on retries.
- 🧩 Framework Agnostic: Use it standalone or plug it seamlessly into Express, Fastify, NestJS, or any custom HTTP server.
- 📡 Built for Scale: Redis adapter for multi-instance deployments with durable message delivery via Streams.
💻 Code Speaks Louder Than Words
Let's look at how incredibly simple it is to set up a Central System (Server) and a Charge Point (Client).
The Server (CSMS)
import { OCPPServer } from "ocpp-ws-io";
const server = new OCPPServer({
protocols: ["ocpp1.6", "ocpp2.0.1"],
logging: { prettify: true, exchangeLog: true, level: "info" }, // Powered by voltlog-io!
});
// Authenticate incoming connections
server.auth((ctx) => {
console.log(`Connection attempt from ${ctx.handshake.identity}`);
ctx.accept({ session: { authorized: true } });
});
server.on("client", (client) => {
console.log(`${client.identity} connected via ${client.protocol}`);
// Type-safe RPC handler
client.handle("ocpp1.6", "BootNotification", ({ params }) => {
return {
status: "Accepted",
currentTime: new Date().toISOString(),
interval: 300,
};
});
});
await server.listen(3000);
console.log("⚡ OCPP Server running on port 3000");
The Client (Charge Point Simulator)
import { OCPPClient, SecurityProfile } from "ocpp-ws-io";
const client = new OCPPClient({
endpoint: "ws://localhost:3000/api/v1/chargers",
identity: "CP001",
protocols: ["ocpp1.6"],
securityProfile: SecurityProfile.NONE,
});
// Handle commands from the central system
client.handle("Reset", ({ params }) => {
console.log("CSMS requested a Reset of type:", params.type);
return { status: "Accepted" };
});
await client.connect();
// Send an RPC Request and await the Result!
const response = await client.call("ocpp1.6", "BootNotification", {
chargePointVendor: "VendorX",
chargePointModel: "ModelY",
});
console.log("Central System response status:", response.status); // Type checked!
🛜 Express-Style Routing & Middleware
One of the standout features of ocpp-ws-io is its robust Routing and Middleware system, designed to feel exactly like Express or Hono. This allows you to build modular, clean, and highly manageable CSMS architectures.
You can intercept HTTP Upgrade requests (Connection Phase), as well as incoming/outgoing OCPP RPC messages (Message Phase).
import { OCPPServer, defineMiddleware } from "ocpp-ws-io";
const server = new OCPPServer({ protocols: ["ocpp1.6"] });
// 1. Connection Middleware: Block bad IPs or rate-limit before WebSockets even open!
const rateLimiter = defineMiddleware(async (ctx, next) => {
if (isRateLimited(ctx.handshake.remoteAddress)) {
ctx.reject(429, "Too Many Requests"); // Instantly drops the connection
} else {
await next();
}
});
server.use(rateLimiter);
// 2. Create dynamic routes with wildcard parameter extraction
const chargerRoute = server.route("/api/v1/chargers/:id");
chargerRoute.on("client", (client) => {
console.log(`Charger connected at endpoint: ${client.handshake.pathname}`);
// 3. Message Middleware: Log processing times for every single RPC call
client.use(async (ctx, next) => {
const start = Date.now();
await next();
console.log(`[${ctx.action}] took ${Date.now() - start}ms`);
});
client.handle("BootNotification", ({ params }) => {
return {
status: "Accepted",
currentTime: new Date().toISOString(),
interval: 300,
};
});
});
await server.listen(3000);
For more advanced routing scenarios: check here
🪵 First-Class Structured Logging (voltlog-io)
High-throughput WebSocket environments are a nightmare to debug with standard console.log. That’s why ocpp-ws-io includes built-in structured JSON logging powered by voltlog-io.
With a single config toggle, you get:
- Extremely fast JSON logging for production.
- Beautiful, colorized output with latency metrics for local development (
prettify: true). -
Exchange Logs (
exchangeLog: true) that perfectly trace every inbound ([IN]) and outbound ([OUT]) OCPP command.
⚡ CP-101 → BootNotification [OUT]
✅ CP-101 ← BootNotification [IN] { latencyMs: 45 }
🌐 The Browser Client
Need to build a Web UI, CSMS Dashboard, or testing interface that talks directly to chargers or proxies? We also ship a zero-dependency Browser Client (ocpp-ws-io/browser) that runs flawlessly in vanilla JS, React, Vue, or Svelte. All the strict type safety from the server, available right in your browser!
🛠️ The ocpp-ws-cli Ecosystem check here
A library without great developer tools is only half the battle. So, along with the core ocpp-ws-io package, we released ocpp-ws-cli: The Ultimate CLI for OCPP developers.
Available instantly via npx ocpp-ws-cli, this toolkit completely transforms how you build and test your backend:
- 🎮
ocpp simulate(Virtual Charge Point): A fully interactive, stateful Terminal UI. It automatically manages the Boot sequence and Heartbeat loop. You get a beautiful real-time dashboard tracking Live Voltage, Current, Power (kW), and SoC (%). Trigger EV plug-ins, swipe virtual RFIDs, send dynamicMeterValuespower curves, or toggle fault states—all from your keyboard! - 📡
ocpp mock: A Server-Sent Events (SSE) Mock Server that instantly streams dummy data (MeterValues, StatusNotification, Heartbeat) to accelerate your Frontend UI development without needing physical hardware. - 🚄
ocpp bench: A server throughput and latency benchmarking engine. Measure real-world performance with min/max/p50/p95/p99 percentiles while tracking connection times and error rates on a live terminal dashboard. - 💣
ocpp load-test: A distributed load engine capable of simulating thousands of simultaneous, staggered Charge Point connections to test how your system handles extreme traffic spikes. - 👾
ocpp fuzz(Protocol Chaos Engine): Protect your CSMS by flooding it with malformed, invalid, or unexpected JSON payloads via multiple concurrent threads to ensure your strict-mode schema handling is bulletproof. - 🔐
ocpp certs: Bypass complicated bash scripts. Instantly auto-generate 4096-bit Root CAs and signed Server/Client.pemcertificates to locally test OCA Profile 2 (TLS) and Profile 3 (Mutual TLS) in seconds! - �️
ocpp audit: A production security wizard that runs automated tests and generates a comprehensive markdown roadmap (audit-report.md) verifying your deployment's strict mode enforcement, WSS handshakes, and caching topologies. - 📝
ocpp generate: Read custom.jsonschemas and automatically construct.d.tsdeclaration libraries for 100% strict type safety across your entire charging network. - 🧪
ocpp test: Execute modularized OCTT compliance test suites directly against your server.
🌟 Get Involved
The EV infrastructure ecosystem is growing rapidly, and robust open-source tools will be the backbone of that growth. Whether you are building the next big CSMS platform, an EV charging app, or just learning about the industry, give ocpp-ws-io a try!
📦 NPM: npm install ocpp-ws-io
🐙 GitHub Repo: rohittiwari-dev/ocpp-ws-io (A ⭐ would be incredibly appreciated!)
📖 Full Documentation: ocpp-ws-io.rohittiwari.me
We are actively looking for feedback, issues, and pull requests! Let me know what you think in the comments below. Happy charging! ⚡🚗
Top comments (0)