Create a Scalable Project Structure

A maintainable REST API should separate application concerns.

Create the following directory structure:

nodejs-rest-api/
│
├── src/
│   ├── config/
│   │   └── database.js
│   │
│   ├── controllers/
│   │   └── user.controller.js
│   │
│   ├── middleware/
│   │   ├── auth.middleware.js
│   │   ├── error.middleware.js
│   │   └── validate.middleware.js
│   │
│   ├── models/
│   │   └── user.model.js
│   │
│   ├── routes/
│   │   ├── index.js
│   │   ├── user.routes.js
│   │   └── auth.routes.js
│   │
│   ├── services/
│   │   ├── user.service.js
│   │   └── auth.service.js
│   │
│   ├── validators/
│   │   ├── user.validator.js
│   │   └── auth.validator.js
│   │
│   ├── utils/
│   │   └── app-error.js
│   │
│   ├── app.js
│   └── server.js
│
├── tests/
│   └── users.test.js
│
├── .env
├── .env.example
├── .gitignore
└── package.json

Responsibilities:

  • config: Database and application configuration.
  • controllers: Handle HTTP requests and responses.
  • middleware: Authentication, validation, and error handling.
  • models: Define MongoDB document structures.
  • routes: Define API endpoints.
  • services: Implement business logic.
  • validators: Define request validation schemas.
  • utils: Reusable utility classes and functions.
  • tests: Automated test cases.

This structure prevents the application from becoming difficult to maintain as more endpoints are added.

Create Project Directories
mkdir -p src/config src/controllers src/middleware src/models src/routes src/services src/validators src/utils tests

Creates the main backend directories. On Windows PowerShell, use New-Item -ItemType Directory -Force with the required directory paths.

Key Takeaways
  • Separate controllers, services, models, and routes.

  • Keep validation and middleware reusable.

  • Organize the project before implementing business logic.