Structuring Modern Web Applications with Hexagonal Architecture
Introduction
Maintaining a clean separation of concerns is the difference between a project that scales and one that becomes a tangled mess. While working on the 'proyecto-dones-2025' initiative, we shifted our focus toward implementing a more robust architectural pattern to handle our growing feature set.
The Architectural Challenge
As our frontend requirements grew, relying solely on tightly coupled service calls led to significant maintenance overhead. We needed a way to decouple our business logic from external dependencies like API clients and UI frameworks. Embracing a Hexagonal Architecture, or "Ports and Adapters," allows us to treat our application core as a black box that remains agnostic of the underlying infrastructure.
Step 1: Defining the Domain Core
By centering our logic on the domain rather than the delivery mechanism, we can define clean interfaces for our services. In our TypeScript-based core, this means defining contracts that any infrastructure layer must fulfill.
interface DataRepository {
fetchItems(): Promise<Item[]>;
}
class DataService {
constructor(private repository: DataRepository) {}
async getProcessedData() {
const data = await this.repository.fetchItems();
return data.filter(item => item.isActive);
}
}
Step 2: Implementing Adapters
We then implement specific adapters for our external concerns, such as communicating with a REST API using Axios or managing authentication through Clerk. This layer effectively acts as the bridge between the outside world and our inner logic.
const apiAdapter = {
fetchItems: async () => {
const response = await axios.get('https://example.com/api/v1/items');
return response.data;
}
};
Step 3: Integrating the UI
With React and Chakra UI, our components remain clean because they only interact with our domain services through dependency injection. This keeps our UI code focused strictly on rendering and user interaction.
function ItemDashboard({ service }) {
const [items, setItems] = useState([]);
useEffect(() => {
service.getProcessedData().then(setItems);
}, [service]);
return <Box>{items.map(i => <Text key={i.id}>{i.name}</Text>)}</Box>;
}
Results
By migrating to this modular structure, we have significantly improved our testability. We can now swap out our data fetching implementation without ever touching the business logic or the UI components. This isolation has reduced the time required to onboard new features by approximately 30%.
Next Steps
Moving forward, we plan to refine our dependency injection container to further automate the wiring of our adapters. We also recommend exploring automated integration testing to ensure that our adapter implementations continue to satisfy the domain contracts as the API evolves.
Generated with Gitvlg.com