Monday, December 15, 2025

🏗️ Understanding the API Layer vs Application Layer

Why db, queue, and utils Belong in src Not src/api in Node.js Backend Architecture

Why These Files Belong in src/ and Not in src/api/

In a clean backend architecture, the API layer and the application layer serve different purposes. The question is: why are these files placed in src/ instead of src/api/?


src/
 ├─ db/prisma.js
 ├─ queue/worker.js
 └─ utils/validators.js
    

1. The API Layer (src/api/)

The API layer contains only the parts of your system that directly handle HTTP requests. These are the components that Express (or any web framework) uses to respond to incoming API calls.

✅ Files that belong inside src/api/:

  • routes
  • controllers
  • models
  • middleware
  • request validators
  • response handlers

These files are the “public interface” of your backend — the part exposed to clients.

2. The Application Layer (src/)

The application layer contains system-wide logic that is not tied to HTTP or Express. These components are used by the entire backend, not just the API.

✅ Files that belong inside src/:

  • database clients
  • queues and workers
  • cron jobs
  • utilities
  • shared helpers
  • business logic services

These are global system components that operate independently of the API layer.

3. Why These Three Files Are Correctly Placed in src/

db/prisma.js

This file initializes your database client. It is used by controllers, services, workers, scripts, and background tasks. Because the database is a system-wide dependency, it does not belong inside the API folder.

queue/worker.js

Workers run background tasks such as message queues, ingestion jobs, notifications, and analytics. They do not serve HTTP requests, so they must live outside the API layer.

utils/validators.js

Validators are shared logic used by controllers, services, workers, and ingestion pipelines. They are not API-specific and therefore belong in the global utilities folder.

4. Clean Architecture Rule

Anything that is not directly tied to HTTP routing belongs in src/, not src/api/.

This separation keeps your project modular, scalable, and easy to maintain.

5. Layman Analogy

Think of your backend like a hospital:

  • src/api/ = Reception + Doctors (they interact with patients/requests)
  • src/ = Entire Hospital Infrastructure (electricity, labs, pharmacy, billing, ambulances)

The infrastructure supports the whole hospital — not just the reception desk. That’s why these files belong in src/.

No comments:

Post a Comment

📊 The immortal Executive Dashboard That Gives You "God" Level Visibility: From Data Overload to Clarity: How This Dashboard Simplifies Your Decisions

Executive Dashboard | HealthTrend Cognitive Platform 🧠 HEALTHTREND COGNITIVE ...