Express.js Coding Standards - mhmunem/Grocery-Comparison-App GitHub Wiki
A well-organized folder structure improves code readability and maintainability. Here's the recommended structure:
├── src/ # Main application code
│ ├── config/ # Configuration files (e.g., environment, database)
│ ├── controllers/ # Business logic for routes
│ ├── middlewares/ # Custom middleware functions
│ ├── models/ # ORM or database models
│ ├── routes/ # API route definitions
│ ├── services/ # Service layer (reusable business logic)
│ ├── utils/ # Helper utilities (e.g., error handlers, logging)
│ └── app.js # Express app initialization
├── .env # Environment variables
├── server.js # Entry point for the application
├── .gitignore # Files and folders to ignore in Git
├── package.json # Project dependencies and scripts
└── README.md # Documentation\
-
Store sensitive information (API keys, database credentials) in a .env file.
-
Use the
dotenv
package to load environment variables:require('dotenv').config(); const PORT = process.env.PORT || 3000;
- Follow the Model-View-Controller (MVC) pattern to separate concerns.
- Controllers handle request-response logic.
- Models interact with the database.
- Routes define API endpoints.
Example:
- Controller (productController.js)
- Service (productService.js)
- Route (productRoutes.js)
- Centralize error handling to avoid duplicating error-handling logic.
- use middleware folder for Error Handling: for eg: src/middlewares/errorHandler.js
use in app.js
:
const errorHandler = require('./middlewares/errorHandler');
app.use(errorHandler);
- Use libraries such as express-validator or some to validate and sanitize input.
const { body, validationResult } = require('express-validator');
- Avoid callback hell and improve readability by using
async/await
.
Bad Practice:
product.find({}, (err, products) => {
if (err) {
return res.status(500).send(err);
}
res.send(products);
});
Good Practice:
const products = await product.find();
res.send(products);
-
Use the
helmet
middleware to secure HTTP headers.const helmet = require('helmet'); app.use(helmet());
-
Use
cors
to configure cross-origin resource sharing.
- Use a logging library for better insight.
- Use docstring
- check for outdated dependencies.
- Regularly update dependencies to avoid vulnerabilities.
- Naming Conventions:
- Use camelCase for variables and functions.
- Use PascalCase for classes.
- Name files descriptively (productController.js, not pro.js).
- Linting:
- Use eslint to enforce consistent code style.
- Code Reviews:
- Ensure every pull request is reviewed before merging to maintain quality.