- Project Structure
/project-root
│
├── /src
│ ├── /config # Configuration files (env variables, DB configs)
│ ├── /controllers # Handles business logic
│ ├── /middlewares # Custom middleware (auth, error handling)
│ ├── /models # Mongoose schemas and models
│ ├── /routes # Route definitions
│ ├── /services # Business logic, API interactions
│ ├── /utils # Helper functions/utilities
│ ├── /validations # Request validation (Joi, express-validator)
│ ├── /jobs # Scheduled tasks/Cron jobs
│ ├── /logs # Logging configurations
│ └── app.js # Express app setup
│
├── /tests # Unit and integration tests
│
├── .env # Environment variables
├── .gitignore # Git ignore rules
├── package.json # Project metadata and dependencies
├── README.md # Project documentation
└── server.js # Application entry point
- Folder Responsibilities
1./config
Central place for configuration files like database connections, environment variables, and third-party API keys.
Example: db.js, appConfig.js
2./controllers
Contains functions to handle incoming requests and responses. This is where business logic is managed.
Example: userController.js, authController.js
3./middlewares
Contains custom middleware functions for tasks like authentication, authorization, logging, and error handling.
Example: authMiddleware.js, errorHandler.js
4./models
Mongoose schemas and models that define the structure of your MongoDB documents.
Example: userModel.js, productModel.js
5./routes
Define all your API endpoints, linking them to their respective controllers.
Example: userRoutes.js, authRoutes.js
6./services
Contains service layer code for complex business logic and external API interactions.
Example: emailService.js, paymentService.js
7./utils
Utility functions and helpers used throughout the application.
Example: generateToken.js, logger.js
8./validations
Request body validation using libraries like Joi or express-validator.
Example: userValidation.js, authValidation.js
9./jobs
For scheduled tasks using libraries like node-cron.
Example: dailyReportJob.js
10./logs
Custom logging setup using winston or similar logging libraries.
Example: logger.js, logConfig.js
11./tests
Unit tests and integration tests using frameworks like Jest, Mocha, or Chai.
Example: user.test.js, auth.test.js
- Key Files Explained
1.server.js
The entry point of the application that starts the Express server.
const app = require('./src/app');
const mongoose = require('mongoose');
require('dotenv').config();
const PORT = process.env.PORT || 5000;
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('MongoDB Connected');
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
}).catch(err => {
console.error('MongoDB connection error:', err);
});
- src/app.js
const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const helmet = require('helmet');
const routes = require('./routes');
const { errorHandler } = require('./middlewares/errorMiddleware');
const app = express();
// Middleware setup
app.use(helmet());
app.use(cors());
app.use(morgan('dev'));
app.use(express.json());
// Routes
app.use('/api', routes);
// Error Handler
app.use(errorHandler);
module.exports = app;
- .env
For storing sensitive data like API keys, database URIs, and environment-specific variables.
PORT=5000
MONGO_URI=mongodb://localhost:27017/your-db
JWT_SECRET=yourSecretKey
- Common Dependencies to Install
npm init -y
npm install express mongoose dotenv cors helmet morgan jsonwebtoken bcryptjs
npm install --save-dev nodemon jest supertest
Express: Web framework.
Mongoose: MongoDB ODM.
dotenv: Load environment variables.
helmet: Security headers.
morgan: Logging.
jsonwebtoken: Authentication.
bcryptjs: Password hashing.
nodemon: Auto-reload during development.
jest/supertest: Testing frameworks.
- Running the Project
npx nodemon server.js
Run Tests:
npm test
This structure is widely used in professional applications and makes it easy to scale and maintain your project. Let me know if you need help setting up specific parts or want to add more advanced features like Docker, Swagger documentation, or CI/CD pipelines! 🚀
Top comments (0)