Organize backend code around business capabilities, such as payments and notifications. When developers change how payments work, they should find the API routes, business rules, and data access code within the payments module.
An Express application might use this structure:
src/
├── app.js
├── infrastructure/
│ ├── database.js
│ └── logger.js
├── middleware/
│ ├── authenticate.js
│ └── handleError.js
├── integrations/
│ ├── emailClient.js
│ └── paymentProcessorClient.js
├── utils/
│ └── parseDate.js
├── constants/
│ └── errorCodes.js
└── modules/
├── notifications/
│ ├── notificationRoutes.js
│ ├── notificationController.js
│ ├── notificationService.js
│ └── data/
│ ├── notificationModel.js
│ └── notificationRepository.js
└── payments/
├── paymentRoutes.js
├── paymentController.js
├── paymentService.js
├── paymentValidation.js
├── data/
│ ├── paymentModel.js
│ ├── paymentRepository.js
│ └── paymentQueries.js
├── helpers/
│ └── calculatePaymentAllocation.js
└── constants/
└── paymentStatuses.jsEach part has a specific responsibility:
- Routes: define API endpoints by connecting HTTP methods and paths, such as
POST /payments, to middleware and controllers. - Controllers: read request data, call services, and return HTTP responses.
- Services: apply business rules and coordinate operations.
- Validation: checks incoming data for required fields, valid types, and allowed values.
- Models: describe stored data and, depending on the database library, define schemas and relationships.
- Repositories: contain database operations, such as finding, saving, and updating records.
- Queries: hold complex queries or aggregation pipelines when they need separate files.
- Helpers: perform focused calculations or transformations.
- Constants: define named values used throughout the module.
The application connects each module’s routes in app.js. For example, mounting paymentRoutes at /payments makes that module responsible for payment endpoints.
For example, a payment route can apply authentication and validation before passing a request to the controller. The controller passes the input to the payment service, which calculates the allocation and asks the repository to save the result. The repository handles the database operation using the payment model. A developer can follow this operation within the payments module.
Shared database connections and logging belong in infrastructure. Common request handling belongs in middleware, and clients for external systems belong in integrations. Keep helpers and constants within a module until other modules need them.
Add files and directories as the complexity requires. A simple repository can contain its own queries; extract them when doing so makes the code easier to follow. These modules can run within one backend application and do not require separate deployments.