mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 14:52:55 +08:00
Regenerate all MDC rules with fresh Exa data and December 2025 best practices
- Refreshed all 241 library rules with current best practices - Updated Exa search results for all libraries with 2025 content - Fixed --regenerate-all flag logic to properly process all libraries - Removed duplicate astro entry in rules.json (merged tags) - Added missing docker.mdc and vim.mdc files - All rules now include modern patterns and anti-patterns - Updated with framework-specific recommendations for 2025 Technical improvements: - Fixed retry_failed_only logic in generate_mdc_files.py - Improved progress tracking for regeneration scenarios - Ensured proper handling of --refresh-exa flag
This commit is contained in:
+393
-294
@@ -1,297 +1,396 @@
|
||||
---
|
||||
description: This rule provides comprehensive guidance on best practices for developing robust, maintainable, and performant Express.js applications, covering aspects from code organization and security to testing and deployment.
|
||||
globs: *.js
|
||||
description: This guide defines definitive best practices for building robust, scalable, and secure Express.js applications, emphasizing modern patterns and common pitfalls.
|
||||
globs: **/*.{js,ts}
|
||||
---
|
||||
- # Express.js Best Practices
|
||||
|
||||
This document outlines best practices for developing Express.js applications to ensure code quality, maintainability, performance, and security.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
- ### Directory Structure Best Practices
|
||||
|
||||
- **Modular Structure:** Organize your application into logical modules based on functionality (e.g., `controllers`, `models`, `routes`, `middleware`, `services`).
|
||||
- **Configuration:** Separate configuration files for different environments (development, production, testing).
|
||||
- **Public Assets:** Keep static assets (CSS, JavaScript, images) in a dedicated `public` directory.
|
||||
- **Views:** Store template files in a `views` directory. Use a template engine like EJS or Pug.
|
||||
- **Example Structure:**
|
||||
|
||||
|
||||
my-express-app/
|
||||
├── controllers/
|
||||
│ ├── userController.js
|
||||
│ └── productController.js
|
||||
├── models/
|
||||
│ ├── user.js
|
||||
│ └── product.js
|
||||
├── routes/
|
||||
│ ├── userRoutes.js
|
||||
│ └── productRoutes.js
|
||||
├── middleware/
|
||||
│ ├── authMiddleware.js
|
||||
│ └── errorMiddleware.js
|
||||
├── services/
|
||||
│ ├── userService.js
|
||||
│ └── productService.js
|
||||
├── config/
|
||||
│ ├── config.js
|
||||
│ └── db.js
|
||||
├── views/
|
||||
│ ├── index.ejs
|
||||
│ └── user.ejs
|
||||
├── public/
|
||||
│ ├── css/
|
||||
│ │ └── style.css
|
||||
│ ├── js/
|
||||
│ │ └── script.js
|
||||
│ └── images/
|
||||
├── app.js # Main application file
|
||||
├── package.json
|
||||
└── .env # Environment variables
|
||||
|
||||
|
||||
- ### File Naming Conventions
|
||||
|
||||
- **Descriptive Names:** Use clear and descriptive names for files and directories.
|
||||
- **Case Convention:** Use camelCase for JavaScript files and directories. For components consider PascalCase.
|
||||
- **Route Files:** Name route files according to the resource they handle (e.g., `userRoutes.js`, `productRoutes.js`).
|
||||
- **Controller Files:** Name controller files according to the resource they handle (e.g., `userController.js`, `productController.js`).
|
||||
- **Model Files:** Name model files after the data model they represent (e.g., `user.js`, `product.js`).
|
||||
|
||||
- ### Module Organization
|
||||
|
||||
- **ES Modules:** Use ES modules (`import`/`export`) for modularity.
|
||||
- **Single Responsibility Principle:** Each module should have a single, well-defined responsibility.
|
||||
- **Loose Coupling:** Minimize dependencies between modules to improve reusability and testability.
|
||||
|
||||
- ### Component Architecture
|
||||
|
||||
- **Reusable Components:** Break down the application into reusable components (e.g., UI components, service components).
|
||||
- **Separation of Concerns:** Separate presentation logic (views) from business logic (controllers/services).
|
||||
- **Component Composition:** Compose complex components from simpler ones.
|
||||
|
||||
- ### Code Splitting Strategies
|
||||
- **Route-Based Splitting:** Split code based on application routes to reduce initial load time. Use dynamic imports (`import()`) to load modules on demand.
|
||||
- **Component-Based Splitting:** Split code based on components, loading components only when they are needed.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
- ### Design Patterns Specific to Express
|
||||
|
||||
- **Middleware Pattern:** Use middleware functions to handle request processing, authentication, logging, etc.
|
||||
- **MVC Pattern:** Implement the Model-View-Controller (MVC) pattern to separate concerns and improve code organization.
|
||||
- **Observer Pattern:** Implement the observer pattern when you need to notify multiple objects about state changes.
|
||||
|
||||
- ### Recommended Approaches for Common Tasks
|
||||
|
||||
- **Route Handling:** Use Express Router to define routes in separate modules.
|
||||
- **Error Handling:** Use custom error handling middleware to catch and handle errors gracefully. See section 6 for more details.
|
||||
- **Data Validation:** Use middleware for validating request data before processing it.
|
||||
- **Asynchronous Operations:** Use `async/await` or Promises to handle asynchronous operations.
|
||||
|
||||
- ### Anti-patterns and Code Smells to Avoid
|
||||
|
||||
- **God Object:** Avoid creating a single, massive object that handles too many responsibilities.
|
||||
- **Callback Hell:** Avoid deeply nested callbacks; use Promises or `async/await` instead.
|
||||
- **Ignoring Errors:** Always handle errors properly instead of ignoring them.
|
||||
- **Global Variables:** Minimize the use of global variables to avoid naming conflicts and unexpected behavior.
|
||||
- **Hardcoding Secrets:** Never hardcode sensitive information (API keys, passwords) in your code. Use environment variables instead.
|
||||
|
||||
- ### State Management Best Practices
|
||||
|
||||
- **Stateless Controllers:** Keep controllers stateless to improve scalability and testability.
|
||||
- **Session Management:** Use session management middleware (e.g., `express-session`) to manage user sessions.
|
||||
- **Caching:** Implement caching strategies (e.g., Redis, Memcached) to improve performance.
|
||||
# express Best Practices
|
||||
|
||||
- ### Error Handling Patterns
|
||||
|
||||
- **Centralized Error Handling:** Create a custom error handling middleware to catch and handle errors from different parts of the application.
|
||||
- **Error Logging:** Log errors to a file or a monitoring service for debugging and analysis.
|
||||
- **Custom Error Objects:** Create custom error objects with specific error codes and messages.
|
||||
- **Graceful Error Messages:** Return user-friendly error messages instead of exposing internal errors.
|
||||
- **Example Error Handler Middleware:**
|
||||
|
||||
javascript
|
||||
// middleware/errorMiddleware.js
|
||||
const errorHandler = (err, req, res, next) => {
|
||||
console.error(err.stack);
|
||||
const statusCode = res.statusCode === 200 ? 500 : res.statusCode;
|
||||
res.status(statusCode);
|
||||
res.json({
|
||||
message: err.message,
|
||||
stack: process.env.NODE_ENV === 'production' ? null : err.stack,
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = errorHandler;
|
||||
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
- ### Optimization Techniques
|
||||
|
||||
- **Gzip Compression:** Use Gzip compression to reduce the size of responses.
|
||||
- **Caching:** Implement caching at different levels (e.g., browser caching, server-side caching) to reduce server load.
|
||||
- **Connection Pooling:** Use connection pooling for database connections to improve performance.
|
||||
- **Load Balancing:** Distribute traffic across multiple servers using a load balancer.
|
||||
|
||||
- ### Memory Management
|
||||
|
||||
- **Avoid Memory Leaks:** Be mindful of memory leaks, especially when working with large datasets or long-running processes. Use tools like `memwatch` to profile.
|
||||
- **Garbage Collection:** Understand how garbage collection works in Node.js and optimize your code accordingly.
|
||||
- **Streams:** Use streams for handling large files or data streams to avoid loading the entire data into memory.
|
||||
|
||||
- ### Rendering Optimization
|
||||
|
||||
- **Template Caching:** Enable template caching in your template engine to improve rendering performance.
|
||||
- **Minify Assets:** Minify CSS and JavaScript files to reduce their size.
|
||||
- **Lazy Loading Images:** Lazy load images to improve initial page load time.
|
||||
|
||||
- ### Bundle Size Optimization
|
||||
|
||||
- **Tree Shaking:** Use tree shaking to remove unused code from your bundles.
|
||||
- **Code Splitting:** Split your code into smaller chunks to reduce the size of initial bundles.
|
||||
- **Dependency Analysis:** Analyze your dependencies to identify and remove unnecessary packages.
|
||||
|
||||
- ### Lazy Loading Strategies
|
||||
|
||||
- **Lazy Load Modules:** Load modules only when they are needed using dynamic imports (`import()`).
|
||||
- **Lazy Load Images and Other Assets:** Use lazy loading for images and other assets that are not immediately visible on the page.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
- ### Common Vulnerabilities and How to Prevent Them
|
||||
|
||||
- **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user input and encoding output.
|
||||
- **Cross-Site Request Forgery (CSRF):** Protect against CSRF attacks by using CSRF tokens.
|
||||
- **SQL Injection:** Use parameterized queries or an ORM to prevent SQL injection attacks.
|
||||
- **NoSQL Injection:** Sanitize user input and avoid constructing queries from strings to prevent NoSQL injection attacks.
|
||||
- **Command Injection:** Avoid executing shell commands based on user input. If necessary, sanitize the input and use appropriate escaping.
|
||||
- **Denial of Service (DoS):** Implement rate limiting and other measures to prevent DoS attacks.
|
||||
- **Man-in-the-Middle (MitM):** Use HTTPS to encrypt communication between the client and server and protect against MitM attacks.
|
||||
- **HTTP Parameter Pollution (HPP):** Avoid using the same parameter multiple times in a request to prevent HPP attacks.
|
||||
|
||||
- ### Input Validation
|
||||
|
||||
- **Server-Side Validation:** Always validate user input on the server-side, even if you have client-side validation.
|
||||
- **Data Sanitization:** Sanitize user input to remove potentially harmful characters or code.
|
||||
- **Schema Validation:** Use schema validation libraries (e.g., Joi, express-validator) to validate request data against a predefined schema.
|
||||
|
||||
- ### Authentication and Authorization Patterns
|
||||
|
||||
- **Authentication:** Use a secure authentication mechanism (e.g., JWT, OAuth) to verify user identities.
|
||||
- **Authorization:** Implement role-based access control (RBAC) or attribute-based access control (ABAC) to control access to resources.
|
||||
- **Secure Password Storage:** Use a strong hashing algorithm (e.g., bcrypt) to store user passwords securely.
|
||||
- **Multi-Factor Authentication (MFA):** Implement MFA to add an extra layer of security.
|
||||
|
||||
- ### Data Protection Strategies
|
||||
|
||||
- **Encryption:** Encrypt sensitive data at rest and in transit.
|
||||
- **Data Masking:** Mask sensitive data in logs and other outputs.
|
||||
- **Access Control:** Restrict access to sensitive data to authorized users and processes.
|
||||
|
||||
- ### Secure API Communication
|
||||
|
||||
- **HTTPS:** Use HTTPS for all API communication.
|
||||
- **API Keys:** Use API keys to authenticate clients.
|
||||
- **Rate Limiting:** Implement rate limiting to prevent abuse and DoS attacks.
|
||||
- **Input Validation:** Validate all input data to prevent injection attacks.
|
||||
- **Output Encoding:** Encode all output data to prevent XSS attacks.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
- ### Unit Testing Strategies
|
||||
|
||||
- **Test-Driven Development (TDD):** Write unit tests before writing the actual code.
|
||||
- **Test Individual Modules:** Test individual modules in isolation to ensure they work correctly.
|
||||
- **Mock Dependencies:** Mock external dependencies (e.g., databases, APIs) to isolate the module being tested.
|
||||
|
||||
- ### Integration Testing
|
||||
|
||||
- **Test Interactions Between Modules:** Test the interactions between different modules to ensure they work together correctly.
|
||||
- **Test API Endpoints:** Test API endpoints to ensure they return the expected results.
|
||||
|
||||
- ### End-to-End Testing
|
||||
|
||||
- **Test the Entire Application Flow:** Test the entire application flow from start to finish.
|
||||
- **Simulate User Interactions:** Simulate user interactions to ensure the application behaves as expected.
|
||||
|
||||
- ### Test Organization
|
||||
|
||||
- **Separate Test Files:** Create separate test files for each module or component.
|
||||
- **Descriptive Test Names:** Use clear and descriptive names for test cases.
|
||||
- **Arrange-Act-Assert Pattern:** Follow the Arrange-Act-Assert pattern in your tests.
|
||||
|
||||
- ### Mocking and Stubbing
|
||||
|
||||
- **Use Mocking Libraries:** Use mocking libraries (e.g., Jest, Sinon) to create mocks and stubs.
|
||||
- **Mock External Dependencies:** Mock external dependencies to isolate the module being tested.
|
||||
- **Stub Function Calls:** Stub function calls to control the behavior of dependencies.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
- ### Frequent Mistakes Developers Make
|
||||
|
||||
- **Not Handling Errors Properly:** Always handle errors properly to prevent unexpected behavior.
|
||||
- **Ignoring Security Vulnerabilities:** Be aware of common security vulnerabilities and take steps to prevent them.
|
||||
- **Not Using Middleware Wisely:** Use middleware wisely to handle common tasks such as authentication, logging, and error handling.
|
||||
- **Over-Engineering:** Avoid over-engineering your code by keeping it simple and focused.
|
||||
|
||||
- ### Edge Cases to Be Aware Of
|
||||
|
||||
- **Handling Large File Uploads:** Use streams or middleware libraries for handling large file uploads to prevent memory issues.
|
||||
- **Dealing with Timezones:** Be aware of timezone issues when working with dates and times.
|
||||
- **Handling Unicode Characters:** Properly handle Unicode characters to prevent encoding issues.
|
||||
- **Dealing with Concurrent Requests:** Implement concurrency control mechanisms to handle concurrent requests safely.
|
||||
|
||||
- ### Version-Specific Issues
|
||||
|
||||
- **Deprecated Features:** Be aware of deprecated features and use the recommended alternatives.
|
||||
- **Breaking Changes:** Be aware of breaking changes when upgrading to a new version of Express.js.
|
||||
|
||||
- ### Compatibility Concerns
|
||||
|
||||
- **Browser Compatibility:** Test your application in different browsers to ensure it works correctly.
|
||||
- **Operating System Compatibility:** Test your application on different operating systems to ensure it works correctly.
|
||||
- **Node.js Version Compatibility:** Ensure your application is compatible with the supported versions of Node.js.
|
||||
|
||||
- ### Debugging Strategies
|
||||
|
||||
- **Use Debugging Tools:** Use debugging tools (e.g., Node.js Inspector, Chrome DevTools) to debug your code.
|
||||
- **Log Statements:** Use log statements to track the flow of execution and identify issues.
|
||||
- **Error Messages:** Read error messages carefully to understand the cause of the error.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
- ### Recommended Development Tools
|
||||
|
||||
- **IDE:** Use a good IDE such as VS Code, WebStorm, or Sublime Text.
|
||||
- **Debugger:** Use a debugger to step through your code and identify issues.
|
||||
- **Linter:** Use a linter (e.g., ESLint) to enforce coding standards.
|
||||
- **Formatter:** Use a formatter (e.g., Prettier) to format your code automatically.
|
||||
|
||||
- ### Build Configuration
|
||||
|
||||
- **Use a Build Tool:** Use a build tool (e.g., Webpack, Parcel) to bundle and optimize your code.
|
||||
- **Configure Build Scripts:** Configure build scripts in your `package.json` file to automate the build process.
|
||||
- **Use Environment Variables:** Use environment variables to configure your application for different environments.
|
||||
|
||||
- ### Linting and Formatting
|
||||
|
||||
- **Use ESLint:** Use ESLint to enforce coding standards and identify potential issues.
|
||||
- **Use Prettier:** Use Prettier to format your code automatically.
|
||||
- **Configure Editor Integration:** Configure your editor to automatically run ESLint and Prettier on save.
|
||||
|
||||
- ### Deployment Best Practices
|
||||
|
||||
- **Use a Process Manager:** Use a process manager (e.g., PM2, Forever) to keep your application running in production.
|
||||
- **Use a Reverse Proxy:** Use a reverse proxy (e.g., Nginx, Apache) to handle incoming requests and forward them to your application.
|
||||
- **Use a Load Balancer:** Use a load balancer to distribute traffic across multiple servers.
|
||||
- **Use HTTPS:** Use HTTPS to encrypt communication between the client and server.
|
||||
- **Monitor Your Application:** Monitor your application to identify and resolve issues.
|
||||
|
||||
- ### CI/CD Integration
|
||||
|
||||
- **Use a CI/CD Pipeline:** Use a CI/CD pipeline (e.g., Jenkins, Travis CI, CircleCI, GitHub Actions) to automate the build, test, and deployment process.
|
||||
- **Run Tests Automatically:** Configure your CI/CD pipeline to run tests automatically on every commit.
|
||||
- **Automate Deployment:** Automate the deployment process to reduce the risk of errors.
|
||||
Express.js is the backbone of many Node.js backends. To build scalable, maintainable, and secure APIs in 2025, you *must* adhere to strict coding standards. This guide provides the definitive rules for our team.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
Adopt a modular, layered architecture. This is non-negotiable for maintainability.
|
||||
|
||||
### 1.1. Enforce a Strict Modular Folder Structure
|
||||
|
||||
Separate concerns into dedicated directories.
|
||||
|
||||
❌ **BAD: Monolithic `server.js`**
|
||||
```javascript
|
||||
// server.js
|
||||
const express = require('express');
|
||||
const app = express();
|
||||
const mongoose = require('mongoose');
|
||||
// ... all models, routes, controllers, middleware here
|
||||
app.get('/users', async (req, res) => { /* ... */ });
|
||||
mongoose.connect('...');
|
||||
app.listen(3000);
|
||||
```
|
||||
|
||||
✅ **GOOD: Layered Structure**
|
||||
```
|
||||
📁 src/
|
||||
├── config/ # Environment variables, DB connection
|
||||
├── controllers/ # Request handling, orchestrates services
|
||||
├── models/ # Mongoose schemas, data access
|
||||
├── routes/ # API endpoint definitions
|
||||
├── middlewares/ # Reusable Express middleware
|
||||
├── services/ # Core business logic
|
||||
├── utils/ # Helper functions
|
||||
├── app.js # Express app setup, middleware, route registration
|
||||
└── server.js # Server start, DB connection, graceful shutdown
|
||||
📁 .env # Environment variables
|
||||
```
|
||||
|
||||
### 1.2. Separate `app.js` from `server.js`
|
||||
|
||||
`app.js` configures the Express application. `server.js` starts the HTTP server and handles infrastructure (DB connection, graceful shutdown). This enables easier testing and deployment.
|
||||
|
||||
**`src/app.js`**
|
||||
```javascript
|
||||
const express = require('express');
|
||||
const helmet = require('helmet');
|
||||
const cors = require('cors');
|
||||
const userRoutes = require('./routes/userRoutes');
|
||||
const { notFound, errorHandler } = require('./middlewares/errorMiddleware');
|
||||
|
||||
const app = express();
|
||||
|
||||
app.use(helmet()); // Essential security headers
|
||||
app.use(cors()); // Enable CORS
|
||||
app.use(express.json()); // Body parser
|
||||
|
||||
app.use('/api/v1/users', userRoutes);
|
||||
|
||||
app.use(notFound);
|
||||
app.use(errorHandler);
|
||||
|
||||
module.exports = app; // Export app for server.js and testing
|
||||
```
|
||||
|
||||
**`src/server.js`**
|
||||
```javascript
|
||||
require('dotenv').config(); // Load .env first
|
||||
const app = require('./app');
|
||||
const connectDB = require('./config/db');
|
||||
const { port } = require('./config/config'); // Centralized config
|
||||
|
||||
connectDB(); // Connect to MongoDB
|
||||
|
||||
const server = app.listen(port, () => {
|
||||
console.log(`Server running on port ${port}`);
|
||||
});
|
||||
|
||||
// Handle unhandled promise rejections
|
||||
process.on('unhandledRejection', (err, promise) => {
|
||||
console.error(`Error: ${err.message}`);
|
||||
server.close(() => process.exit(1));
|
||||
});
|
||||
```
|
||||
|
||||
## 2. Environment Management
|
||||
|
||||
Never hardcode sensitive information.
|
||||
|
||||
### 2.1. Use `.env` for Configuration and Secrets
|
||||
|
||||
Store all configuration and secrets in `.env` files and load them with `dotenv`.
|
||||
|
||||
❌ **BAD: Hardcoded secrets**
|
||||
```javascript
|
||||
// config.js
|
||||
const DB_URI = 'mongodb://user:password@localhost:27017/mydb';
|
||||
const JWT_SECRET = 'supersecretkey';
|
||||
```
|
||||
|
||||
✅ **GOOD: `.env` and `dotenv`**
|
||||
**`.env`**
|
||||
```
|
||||
PORT=5000
|
||||
MONGO_URI=mongodb://user:password@localhost:27017/mydb
|
||||
JWT_SECRET=a_very_secure_random_string_for_jwt
|
||||
```
|
||||
**`src/config/config.js`**
|
||||
```javascript
|
||||
require('dotenv').config();
|
||||
|
||||
module.exports = {
|
||||
port: process.env.PORT || 3000,
|
||||
mongoURI: process.env.MONGO_URI,
|
||||
jwtSecret: process.env.JWT_SECRET,
|
||||
nodeEnv: process.env.NODE_ENV || 'development',
|
||||
};
|
||||
```
|
||||
|
||||
## 3. Common Patterns and Anti-patterns
|
||||
|
||||
Embrace modern JavaScript and robust patterns.
|
||||
|
||||
### 3.1. Always Use `async/await` for Asynchronous Operations
|
||||
|
||||
Avoid callback hell and `.then()` chains.
|
||||
|
||||
❌ **BAD: Callback hell or `.then()` chains**
|
||||
```javascript
|
||||
// userController.js
|
||||
exports.getUsers = (req, res) => {
|
||||
User.find().then(users => {
|
||||
res.json(users);
|
||||
}).catch(err => {
|
||||
res.status(500).json({ message: err.message });
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
✅ **GOOD: `async/await` with `express-async-handler`**
|
||||
Install `npm i express-async-handler`. This eliminates repetitive `try/catch` blocks in controllers.
|
||||
|
||||
**`src/controllers/userController.js`**
|
||||
```javascript
|
||||
const asyncHandler = require('express-async-handler');
|
||||
const userService = require('../services/userService');
|
||||
|
||||
exports.getUsers = asyncHandler(async (req, res) => {
|
||||
const users = await userService.getAllUsers();
|
||||
res.json(users);
|
||||
});
|
||||
|
||||
exports.createUser = asyncHandler(async (req, res) => {
|
||||
const newUser = await userService.createUser(req.body);
|
||||
res.status(201).json(newUser);
|
||||
});
|
||||
```
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
Security is paramount. Implement these from day one.
|
||||
|
||||
### 4.1. Validate and Sanitize All User Input
|
||||
|
||||
Never trust client-side data. Use libraries like `Joi` or `zod`.
|
||||
|
||||
❌ **BAD: No input validation**
|
||||
```javascript
|
||||
// userController.js
|
||||
exports.createUser = asyncHandler(async (req, res) => {
|
||||
const newUser = new User(req.body); // Directly use req.body
|
||||
await newUser.save();
|
||||
res.status(201).json(newUser);
|
||||
});
|
||||
```
|
||||
|
||||
✅ **GOOD: Input Validation with `Joi`**
|
||||
Install `npm i joi`.
|
||||
**`src/validation/userValidation.js`**
|
||||
```javascript
|
||||
const Joi = require('joi');
|
||||
|
||||
const userSchema = Joi.object({
|
||||
username: Joi.string().alphanum().min(3).max(30).required(),
|
||||
email: Joi.string().email().required(),
|
||||
password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')).required(),
|
||||
});
|
||||
|
||||
exports.validateUser = (req, res, next) => {
|
||||
const { error } = userSchema.validate(req.body);
|
||||
if (error) {
|
||||
return res.status(400).json({ message: error.details[0].message });
|
||||
}
|
||||
next();
|
||||
};
|
||||
```
|
||||
**`src/routes/userRoutes.js`**
|
||||
```javascript
|
||||
const router = require('express').Router();
|
||||
const { createUser } = require('../controllers/userController');
|
||||
const { validateUser } = require('../validation/userValidation');
|
||||
|
||||
router.post('/', validateUser, createUser);
|
||||
```
|
||||
|
||||
### 4.2. Use Security Middleware (`helmet`, `cors`, `express-rate-limit`)
|
||||
|
||||
Protect your API from common web vulnerabilities.
|
||||
|
||||
**`src/app.js` (already shown, but reiterating)**
|
||||
```javascript
|
||||
const express = require('express');
|
||||
const helmet = require('helmet'); // Sets various HTTP headers for security
|
||||
const cors = require('cors'); // Enables CORS with configurable options
|
||||
const rateLimit = require('express-rate-limit'); // Basic rate limiting
|
||||
|
||||
const app = express();
|
||||
|
||||
app.use(helmet());
|
||||
app.use(cors({ origin: process.env.CORS_ORIGIN || '*', credentials: true })); // Configure origin
|
||||
app.use(rateLimit({
|
||||
windowMs: 15 * 60 * 1000, // 15 minutes
|
||||
max: 100, // Limit each IP to 100 requests per windowMs
|
||||
message: 'Too many requests from this IP, please try again after 15 minutes',
|
||||
}));
|
||||
// ... other middleware and routes
|
||||
```
|
||||
|
||||
### 4.3. Secure Cookies
|
||||
|
||||
Always set `httpOnly`, `secure`, and `SameSite` attributes for session cookies.
|
||||
|
||||
❌ **BAD: Insecure cookies**
|
||||
```javascript
|
||||
res.cookie('token', token);
|
||||
```
|
||||
|
||||
✅ **GOOD: Secure cookies**
|
||||
```javascript
|
||||
res.cookie('token', token, {
|
||||
httpOnly: true, // Prevents client-side JS access
|
||||
secure: process.env.NODE_ENV === 'production', // Only send over HTTPS
|
||||
sameSite: 'Strict', // Protects against CSRF
|
||||
maxAge: 3600000, // 1 hour
|
||||
});
|
||||
```
|
||||
|
||||
## 5. Error Handling
|
||||
|
||||
Centralize and standardize error responses.
|
||||
|
||||
### 5.1. Implement Centralized Error Handling Middleware
|
||||
|
||||
Catch all errors and return consistent JSON responses.
|
||||
|
||||
**`src/middlewares/errorMiddleware.js`**
|
||||
```javascript
|
||||
const { nodeEnv } = require('../config/config');
|
||||
|
||||
const notFound = (req, res, next) => {
|
||||
const error = new Error(`Not Found - ${req.originalUrl}`);
|
||||
res.status(404);
|
||||
next(error);
|
||||
};
|
||||
|
||||
const errorHandler = (err, req, res, next) => {
|
||||
const statusCode = res.statusCode === 200 ? 500 : res.statusCode;
|
||||
res.status(statusCode);
|
||||
res.json({
|
||||
message: err.message,
|
||||
stack: nodeEnv === 'production' ? '🥞' : err.stack, // Hide stack in prod
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = { notFound, errorHandler };
|
||||
```
|
||||
**`src/app.js` (already shown, but reiterating)**
|
||||
```javascript
|
||||
// ...
|
||||
app.use(notFound);
|
||||
app.use(errorHandler);
|
||||
// ...
|
||||
```
|
||||
|
||||
## 6. API Design
|
||||
|
||||
Design APIs for clarity, consistency, and future growth.
|
||||
|
||||
### 6.1. Follow RESTful Principles and Version Your API
|
||||
|
||||
Use clear resource-based URLs and HTTP methods. Versioning prevents breaking changes.
|
||||
|
||||
❌ **BAD: Inconsistent, unversioned endpoints**
|
||||
```javascript
|
||||
app.get('/getAllUsers', /* ... */);
|
||||
app.post('/addUser', /* ... */);
|
||||
```
|
||||
|
||||
✅ **GOOD: RESTful and Versioned**
|
||||
```javascript
|
||||
// src/routes/userRoutes.js
|
||||
router.get('/', getUsers); // GET /api/v1/users
|
||||
router.post('/', createUser); // POST /api/v1/users
|
||||
router.get('/:id', getUserById); // GET /api/v1/users/:id
|
||||
router.put('/:id', updateUser); // PUT /api/v1/users/:id
|
||||
router.delete('/:id', deleteUser); // DELETE /api/v1/users/:id
|
||||
```
|
||||
**`src/app.js`**
|
||||
```javascript
|
||||
app.use('/api/v1/users', userRoutes);
|
||||
```
|
||||
|
||||
## 7. Performance Considerations
|
||||
|
||||
Optimize for speed and efficiency.
|
||||
|
||||
### 7.1. Enable Gzip/Brotli Compression
|
||||
|
||||
Reduce response payload size.
|
||||
|
||||
Install `npm i compression`.
|
||||
**`src/app.js`**
|
||||
```javascript
|
||||
const express = require('express');
|
||||
const compression = require('compression'); // Import compression
|
||||
|
||||
const app = express();
|
||||
|
||||
app.use(compression()); // Use compression middleware early
|
||||
// ... other middleware and routes
|
||||
```
|
||||
|
||||
## 8. Testing Approaches
|
||||
|
||||
Ensure reliability and prevent regressions.
|
||||
|
||||
### 8.1. Implement Unit and Integration Tests
|
||||
|
||||
Use `Jest` and `Supertest` for comprehensive testing.
|
||||
|
||||
Install `npm i --save-dev jest supertest`.
|
||||
**`package.json`**
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"test": "jest --detectOpenHandles"
|
||||
}
|
||||
}
|
||||
```
|
||||
**`src/tests/user.test.js`**
|
||||
```javascript
|
||||
const request = require('supertest');
|
||||
const app = require('../app'); // Test your app.js directly
|
||||
const mongoose = require('mongoose');
|
||||
const User = require('../models/User');
|
||||
const { mongoURI } = require('../config/config');
|
||||
|
||||
beforeAll(async () => {
|
||||
await mongoose.connect(mongoURI);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await User.deleteMany({}); // Clean up after each test
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await mongoose.connection.close();
|
||||
});
|
||||
|
||||
describe('User API', () => {
|
||||
it('should create a new user', async () => {
|
||||
const res = await request(app)
|
||||
.post('/api/v1/users')
|
||||
.send({
|
||||
username: 'testuser',
|
||||
email: 'test@example.com',
|
||||
password: 'password123'
|
||||
});
|
||||
expect(res.statusCode).toEqual(201);
|
||||
expect(res.body).toHaveProperty('username', 'testuser');
|
||||
});
|
||||
|
||||
it('should fetch all users', async () => {
|
||||
await request(app).post('/api/v1/users').send({ username: 'u1', email: 'u1@e.com', password: 'p1' });
|
||||
await request(app).post('/api/v1/users').send({ username: 'u2', email: 'u2@e.com', password: 'p2' });
|
||||
|
||||
const res = await request(app).get('/api/v1/users');
|
||||
expect(res.statusCode).toEqual(200);
|
||||
expect(res.body.length).toEqual(2);
|
||||
});
|
||||
});
|
||||
```
|
||||
Reference in New Issue
Block a user