A standard structure for building organized and scalable Node.js backends, especially with Express and MongoDB (via Mongoose).
✨ It's just an overview — we’ll learn this throughout the notes!
project-root/
│
├── 📁 src/ ← All source code lives here
│ ├── 📁 config/ ← Configuration files (DB, environment)
│ ├── 📁 controllers/ ← Route handlers (business logic)
│ ├── 📁 routes/ ← Express route definitions
│ ├── 📁 models/ ← Mongoose schemas or DB models
│ ├── 📁 middlewares/ ← Custom middleware (auth, logger, error handler)
│ ├── 📁 services/ ← Business logic (email, upload, etc.)
│ ├── 📁 utils/ ← Helper functions (e.g., formatters, generators)
│ ├── 📁 validations/ ← Joi/Yup request schema validators
│ ├── 📁 constants/ ← Static config (roles, status codes)
│ └── app.js ← Express app config
│
├── 📄 .env ← Environment variables
├── 📄 .gitignore ← Ignore node_modules, .env, etc.
├── 📄 package.json ← Project metadata & dependencies
├── 📄 server.js ← App entry point (starts the server)
└── 📄 README.md ← Project documentation
| Folder / File | Purpose |
|---|---|
src/config |
MongoDB config, app settings, 3rd-party API keys |
src/controllers |
Logic for handling requests/responses |
src/routes |
URL paths and associated controllers |
src/models |
Mongoose schemas or database models |
src/middlewares |
Auth, error handling, validation logic |
src/services |
Reusable business logic like sending emails or hashing passwords |
src/utils |
Pure utility functions (formatters, generators) |
src/validations |
Input validation rules using Joi, Yup, or custom logic |
src/constants |
Reusable static values like user roles, error messages |
src/app.js |
Main Express app setup file |
server.js |
Loads and runs app.js, listens on a port |
server.js
const app = require('./src/app');
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`🚀 Server running on port ${PORT}`);
});
app.js
const express = require('express');
const dotenv = require('dotenv');
const noteRoutes = require('./routes/noteRoutes');
const connectDB = require('./config/db');
dotenv.config();
connectDB();
const app = express();
app.use(express.json());
app.use('/api/notes', noteRoutes);
module.exports = app;
.env and dotenv for secure configs