Node.js › Architecture & Design Patterns
What is a Hexagonal Architecture (Ports and Adapters), and what specific benefit does it provide for a Node.js API?
AdvancedAnswer
Hexagonal Architecture structures an application so the core business logic sits in the center, communicating with the outside world (databases, HTTP frameworks, message queues, third-party APIs) only through defined interfaces called 'ports', with concrete implementations ('adapters') plugged in at the edges -- this means the core business logic has zero direct dependency on Express, MongoDB, or any other specific technology, making it possible to swap the web framework or database with minimal changes to the actual business rules, and to test the core logic in complete isolation.
// Port (interface the core logic depends on)
class NotificationPort { async send(message) { throw new Error('not implemented'); } }
// Adapter (concrete implementation, plugged in at the edge)
class EmailAdapter extends NotificationPort {
async send(message) { return emailClient.send(message); }
}
// Core business logic depends only on the port, not the concrete adapter
class OrderService {
constructor(notificationPort) { this.notifications = notificationPort; }
async completeOrder(order) { await this.notifications.send(`Order ${order.id} completed`); }
}Real-world example A startup initially ships with an EmailAdapter for order notifications, then later adds an SmsAdapter and a SlackAdapter, all implementing the same NotificationPort interface, without ever having to touch the core OrderService business logic that triggers the notification.