diff --git a/backend/expressjs/readme.md b/backend/expressjs/readme.md index a93e5d9..47e7364 100644 --- a/backend/expressjs/readme.md +++ b/backend/expressjs/readme.md @@ -64,6 +64,8 @@ app.post('/api/users', async (req, res) => { /* бизнес-логика здесь */ }); ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript router.post('/api/users', UserController.create); @@ -75,14 +77,13 @@ class UserController { ### 🚀 Solution Роутер только описывает эндпоинты, Контроллер извлекает данные запроса и отдает ответ. Логика — в Сервисах. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 2. Async/Await Error Wrapping (Express 4) ### ❌ Bad Practice ```javascript router.get('/', async (req, res) => { throw new Error('Crash'); }); // Express 4 не ловит rejection ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const asyncHandler = fn => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next); @@ -91,14 +92,13 @@ router.get('/', asyncHandler(UserController.get)); ### 🚀 Solution В Express 4 всегда оборачивайте async-маршруты в `asyncHandler`, чтобы пробрасывать ошибки в глобальный Error Handler. (В Express 5 это встроено). - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 3. Global Error Handler Middleware ### ❌ Bad Practice ```javascript app.use((req, res) => res.status(404).send('Not Found')); // Нет ловца ошибок 500 ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript app.use((err, req, res, next) => { @@ -109,14 +109,13 @@ app.use((err, req, res, next) => { ### 🚀 Solution Определите единую middleware с 4 аргументами `(err, req, res, next)` в самом конце пайплайна для перехвата всех сбоев. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 4. Request Payload Validation (Joi / Zod) ### ❌ Bad Practice ```javascript if (!req.body.email || req.body.age < 18) return res.status(400); // Ручная проверка ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const validate = schema => (req, res, next) => { @@ -129,14 +128,13 @@ router.post('/', validate(userSchema), UserController.create); ### 🚀 Solution Проверяйте тело и параметры запросов на уровне Middleware с помощью надежных библиотек валидации (Joi, Zod), не пуская мусор в контроллеры. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 5. Environment Variables separation ### ❌ Bad Practice ```javascript mongoose.connect('mongodb://admin:pass@host/db'); // Хардкод секретов ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript require('dotenv').config(); @@ -145,12 +143,11 @@ mongoose.connect(process.env.DB_URI); ### 🚀 Solution Используйте `dotenv` и конфигурационные файлы для разных окружений. Секреты хранятся только в `.env` (который добавлен в `.gitignore`). - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 6. HTTP Security Headers (Helmet) ### ❌ Bad Practice // Приложение светит 'X-Powered-By: Express' +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const helmet = require('helmet'); @@ -159,14 +156,13 @@ app.use(helmet()); ### 🚀 Solution Используйте `helmet` для автоматической защиты от XSS, clickjacking и скрытия заголовков фреймворка из коробки. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 7. Cross-Origin Resource Sharing (CORS) ### ❌ Bad Practice ```javascript app.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); next(); }); ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const cors = require('cors'); @@ -175,12 +171,11 @@ app.use(cors({ origin: 'https://myapp.com', credentials: true })); ### 🚀 Solution Используйте официальный модуль `cors`. Разрешайте доступ только доверенным доменам, а не всем подряд (`*`). - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 8. Rate Limiting (Защита от DDoS) ### ❌ Bad Practice // API открыт для миллиона запросов в секунду +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const rateLimit = require('express-rate-limit'); @@ -189,14 +184,13 @@ app.use('/api/', rateLimit({ windowMs: 15 * 60 * 1000, max: 100 })); ### 🚀 Solution Защищайте все эндпоинты (а особенно авторизацию) встроенным лимитером запросов. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 9. Body Parsing & Payload Limits ### ❌ Bad Practice ```javascript app.use(express.json()); // Злоумышленник может отправить 500Мб JSON ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript app.use(express.json({ limit: '10kb' })); @@ -205,14 +199,13 @@ app.use(express.urlencoded({ extended: true, limit: '10kb' })); ### 🚀 Solution Строго ограничивайте размер принимаемого JSON через опцию `limit`, чтобы предотвратить исчерпание RAM. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 10. Centralized Logging (Morgan + Winston) ### ❌ Bad Practice ```javascript console.log('User signed in'); ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript app.use(morgan('combined', { stream: winstonLogger.stream })); @@ -221,14 +214,13 @@ winstonLogger.info('User signed in'); ### 🚀 Solution Заменяйте `console.log` на логгеры вроде Winston (с уровнями log/warn/error) и Morgan (для фиксации HTTP-запросов). - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 11. Database Connection Management ### ❌ Bad Practice ```javascript // Коннект к базе делается перед каждым запросом ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript mongoose.connect(process.env.DB_URI).then(() => { @@ -238,14 +230,13 @@ mongoose.connect(process.env.DB_URI).then(() => { ### 🚀 Solution Открывайте единый пул подключений к БД (Connection Pool) при запуске приложения и используйте его во всех контроллерах. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 12. JWT Authentication Middleware ### ❌ Bad Practice ```javascript // Проверка токена встроена в контроллер профиля ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const authGuard = (req, res, next) => { @@ -258,14 +249,13 @@ const authGuard = (req, res, next) => { ### 🚀 Solution Аутентификация должна представлять собой изолированную Middleware, которая вешается на защищенные маршруты и прикрепляет объект `req.user`. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 13. Role-Based Access Control (RBAC) Middleware ### ❌ Bad Practice ```javascript if (req.user.role !== 'admin') return res.status(403); ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const requireRole = (...roles) => (req, res, next) => { @@ -277,14 +267,13 @@ router.delete('/:id', requireRole('admin', 'manager'), Controller.del); ### 🚀 Solution Доступ к маршрутам по ролям должен задаваться декларативно через Middleware. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 14. Standard API Response Wrapper ### ❌ Bad Practice ```javascript res.json({ foo: 'bar' }); // Каждый метод возвращает случайную структуру ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript class ApiResponse { @@ -295,14 +284,13 @@ class ApiResponse { ### 🚀 Solution Используйте единый класс-утилиту для отправки ответов, чтобы клиент всегда ожидал `success` и `data`/`error` поля. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 15. Pagination details in API ### ❌ Bad Practice ```javascript res.json(users); // Выбросить миллион записей ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const page = parseInt(req.query.page) || 1; @@ -312,12 +300,11 @@ res.json({ data: users, meta: { total, page, limit, pages: Math.ceil(total/limit ### 🚀 Solution Любой список сущностей обязан иметь пагинацию (Offset или Cursor) и секцию `meta` в ответе. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 16. Graceful Shutdown ### ❌ Bad Practice // При получении SIGTERM сервер моментально обрывает процессы +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript process.on('SIGTERM', () => { @@ -329,12 +316,11 @@ process.on('SIGTERM', () => { ### 🚀 Solution Корректно закрывайте активные HTTP-сессии и пулы подключений к БД перед остановкой контейнера. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 17. 404 Route Handler ### ❌ Bad Practice // Если роут не найден, возвращается пустая белая страница +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript app.use('*', (req, res) => { @@ -344,15 +330,14 @@ app.use('*', (req, res) => { ### 🚀 Solution Поместите этот обработчик ПОСЛЕ всех ваших маршрутов (но ДО глобального обработчика ошибок). - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 18. Application Structure (Folder organization) ### ❌ Bad Practice ``` /routes.js /app.js // Монолит на 5000 строк ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ``` src/ @@ -365,12 +350,11 @@ src/ ### 🚀 Solution Строго разделяйте проект на логические папки. Имплементируйте многослойную архитектуру. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 19. Health Check Endpoint ### ❌ Bad Practice // Нет проверки жизнеспособности подов Kubernetes +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript app.get('/health', (req, res) => { @@ -380,14 +364,13 @@ app.get('/health', (req, res) => { ### 🚀 Solution Всегда имейте эндпоинт `/health` для систем мониторинга, балансировщиков и Health Probes. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 20. Data Sanitization (XSS / NoSQL Injection) ### ❌ Bad Practice ```javascript User.find({ username: req.body.username }); // body.username = { "$gt": "" } ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const mongoSanitize = require('express-mongo-sanitize'); @@ -398,12 +381,11 @@ app.use(xss()); ### 🚀 Solution Защищайте БД от NoSQL-инъекций и XSS скриптов, очищая `req.body` и `req.query`. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 21. Swagger / OpenAPI documentation ### ❌ Bad Practice // Документация в стороннем Word-файле +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const swaggerUi = require('swagger-ui-express'); @@ -413,14 +395,13 @@ app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); ### 🚀 Solution Генерируйте или обслуживайте API-документацию прямо в приложении (Swagger, OpenAPI). - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 22. Manual Dependency Injection ### ❌ Bad Practice ```javascript const UserService = require('./UserService'); // Прямой импорт, невозможно тестировать ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript class UserController { @@ -431,12 +412,11 @@ const controller = new UserController(new UserService(db)); ### 🚀 Solution Если не используете IoC (Awilix), инжектируйте зависимости вручную для облегчения Unit-тестирования. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 23. File Uploads (Multer) ### ❌ Bad Practice // Парсинг бинарников руками +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const multer = require('multer'); @@ -446,15 +426,14 @@ router.post('/avatar', upload.single('file'), Controller.upload); ### 🚀 Solution Используйте `multer` с обязательным ограничением размера файла (`limits`), чтобы обезопасить сервер от переполнения диска. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 24. Event Emitters (Фоновые задачи) ### ❌ Bad Practice ```javascript await emailService.send(); // Блокировка респонса res.send('Welcome'); ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const EventEmitter = require('events'); @@ -467,12 +446,11 @@ res.send('Welcome'); ### 🚀 Solution Снимайте длительные задачи с основного потока ответа с помощью нативных Events NodeJS. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 25. Caching (Redis Middleware) ### ❌ Bad Practice // БД обрабатывает сложные расчеты на каждый хит +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const cacheMiddleware = (req, res, next) => { @@ -485,14 +463,13 @@ const cacheMiddleware = (req, res, next) => { ### 🚀 Solution Используйте кэширование (Redis) для GET-запросов, результат которых меняется редко. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 26. Custom Error Classes ### ❌ Bad Practice ```javascript throw new Error('Not found'); ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript class AppError extends Error { @@ -507,14 +484,13 @@ throw new AppError('User not found', 404); ### 🚀 Solution Создавайте кастомные классы ошибок, чтобы глобальный логгер мог отличать операционные ошибки (Operational) от фатальных крашей кода. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 27. Proxy Trust in Production ### ❌ Bad Practice ```javascript req.ip // Дает '127.0.0.1' через Nginx ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript app.set('trust proxy', 1); // Доверяем первому прокси @@ -522,15 +498,14 @@ app.set('trust proxy', 1); // Доверяем первому прокси ### 🚀 Solution Если Express стоит за Nginx / AWS ELB, включите `trust proxy`, чтобы получать реальные IP пользователей. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 28. Separating Server from App ### ❌ Bad Practice ```javascript // app.js app.listen(3000); // Мешает интеграционным тестам ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript // app.js @@ -543,12 +518,11 @@ app.listen(3000); ### 🚀 Solution Экспортируйте Express App отдельно от `listen`, чтобы `supertest` мог легко запускать тесты на случайных портах. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 29. UUID Request Correlation ### ❌ Bad Practice // Ошибки в логах невозможно связать с конкретным пользователем +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const { v4: uuidv4 } = require('uuid'); @@ -561,12 +535,11 @@ app.use((req, res, next) => { ### 🚀 Solution Устанавливайте уникальный ID каждому запросу для отслеживания его пути по всем логам и микросервисам. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 30. Secure Session Management ### ❌ Bad Practice // Сессия хранится в памяти (MemoryStore) с открытыми куками +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript app.use(session({ @@ -584,7 +557,3 @@ app.use(session({
Применяйте данные паттерны для построения максимально безопасной, быстрой и прозрачной архитектуры на Express.js! 🚂
- - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. diff --git a/backend/mongodb/readme.md b/backend/mongodb/readme.md index 257ed72..8c20ab2 100644 --- a/backend/mongodb/readme.md +++ b/backend/mongodb/readme.md @@ -41,6 +41,8 @@ For deep dives into specific topics, consult the specialized guides: // Inserting data without validation db.users.insertOne({ name: "John", age: -5, admin: true }); ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice Implement strict schema validation using JSON Schema in MongoDB. #### 🚀 Solution @@ -72,8 +74,6 @@ db.createCollection("users", { ``` -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. --- [⬆ Back to Top](#-mongodb-production-ready-best-practices) diff --git a/backend/nestjs/readme.md b/backend/nestjs/readme.md index b4c238b..ea165e5 100644 --- a/backend/nestjs/readme.md +++ b/backend/nestjs/readme.md @@ -64,6 +64,8 @@ export class UsersService { constructor(@InjectRepository(User) private repo: Repository) {} // Жесткая привязка к TypeORM } ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript @Injectable() @@ -82,6 +84,8 @@ create(@Body() dto: CreateUserDto) { if (!dto.email) throw new BadRequestException('Email required'); } ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript // main.ts @@ -96,6 +100,8 @@ app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: t @Post() create(@Body() body: unknown) {} // Потеря типизации ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript export class CreateUserDto { @@ -117,6 +123,8 @@ async createUser(@Body() dto: CreateDto) { return this.db.users.create({ ...dto, hash }); } ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript @Post() @@ -132,6 +140,8 @@ async createUser(@Body() dto: CreateDto) { ```typescript try { ... } catch (e) { throw new HttpException('Error', 500); } ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript @Catch() @@ -149,6 +159,8 @@ app.useGlobalFilters(new AllExceptionsFilter()); ```typescript TypeOrmModule.forRoot({ url: process.env.DB_URL }) // Переменные могут быть еще не загружены ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript TypeOrmModule.forRootAsync({ @@ -165,6 +177,8 @@ TypeOrmModule.forRootAsync({ ```typescript const secret = process.env.JWT_SECRET; // Прямой вызов ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript constructor(private configService: ConfigService) {} @@ -179,6 +193,8 @@ const secret = this.configService.get('JWT_SECRET'); @Get() getProfile(@Req() req: Request) { return req.user; } ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript export const CurrentUser = createParamDecorator((data, ctx: ExecutionContext) => ctx.switchToHttp().getRequest().user); @@ -195,6 +211,8 @@ getProfile(@CurrentUser() user: UserEntity) { return user; } @Get() getData(@Req() req) { if (!req.headers.auth) throw new UnauthorizedException(); } ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript @UseGuards(JwtAuthGuard) @@ -210,6 +228,8 @@ getData() {} @Get() getAdminData(@CurrentUser() user) { if (user.role !== 'ADMIN') throw new ForbiddenException(); } ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript @Roles('ADMIN') @@ -226,6 +246,8 @@ getAdminData() {} @Get(':id') getUser(@Param('id') id: string) { const userId = parseInt(id, 10); } ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript @Get(':id') @@ -239,6 +261,8 @@ getUser(@Param('id', ParseIntPipe) id: number) {} ```typescript return { success: true, data: result, timestamp: new Date() }; // Дублирование везде ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript @Injectable() @@ -255,6 +279,8 @@ export class TransformInterceptor implements NestInterceptor { @Get() getData() { console.log('Request started'); /* ... */ console.log('Done'); } ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript @Injectable() @@ -273,6 +299,8 @@ export class LoggingInterceptor implements NestInterceptor { ```typescript await this.repo1.save(data1); await this.repo2.save(data2); // Нет транзакции ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript await this.dataSource.transaction(async manager => { @@ -289,6 +317,8 @@ await this.dataSource.transaction(async manager => { // Нет никаких аннотаций DTO export class CreateDogDto { name: string; } ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript export class CreateDogDto { @@ -302,6 +332,8 @@ export class CreateDogDto { ### 🚨 16. Rate Limiting (ThrottlerModule) #### ❌ Bad Practice // Нет защиты от DDoS и брутфорса +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript // app.module.ts @@ -313,6 +345,8 @@ ThrottlerModule.forRoot([{ ttl: 60000, limit: 10 }]) ### 🚨 17. Caching Results #### ❌ Bad Practice // Каждый запрос делает тяжелый расчет в БД +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript @UseInterceptors(CacheInterceptor) @@ -329,6 +363,8 @@ getStats() {} await this.userService.create(); await this.emailService.send(); // Жесткая привязка зависимостей ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript await this.userService.create(); @@ -342,6 +378,8 @@ this.eventEmitter.emit('user.created', new UserCreatedEvent(user)); ```typescript setInterval(() => this.cleanupData(), 1000 * 60 * 60); ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT) @@ -355,6 +393,8 @@ handleCron() { this.cleanupData(); } ```typescript @Post() // Использование HTTP для межсервисного общения ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript @MessagePattern({ cmd: 'get_user' }) @@ -368,6 +408,8 @@ getUser(data: unknown) { return this.userService.findById(data.id); } ```typescript @Get('ping') ping() { return 'pong'; } ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript @Get('health') @@ -383,6 +425,8 @@ check() { return this.health.check([() => this.db.pingCheck('database')]); } // UserService -> AuthService -> UserService @Injectable() class UserService { constructor(private auth: AuthService) {} } ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript @Injectable() class UserService { constructor(@Inject(forwardRef(() => AuthService)) private auth: AuthService) {} } @@ -395,6 +439,8 @@ check() { return this.health.check([() => this.db.pingCheck('database')]); } ```typescript // Модуль B импортирует Модуль А, Модуль С импортирует Модуль А... ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript @Module({ imports: [DatabaseModule], exports: [DatabaseModule] }) @@ -406,6 +452,8 @@ export class CoreModule {} // Глобальный фасад ### 🚨 24. Global Middleware #### ❌ Bad Practice // Определение логгера запросов в каждом месте +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript export class AppModule implements NestModule { @@ -420,6 +468,8 @@ export class AppModule implements NestModule { ```typescript const service = new UserService(new Database()); // Реальная БД в тестах ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript const module = await Test.createTestingModule({ @@ -434,6 +484,8 @@ const module = await Test.createTestingModule({ ```typescript if (!isEmailUnique(dto.email)) throw error; // Ручная логика в сервисе ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript @ValidatorConstraint({ async: true }) @@ -447,6 +499,8 @@ export class IsUniqueConstraint implements ValidatorConstraintInterface { ... } ### 🚨 27. File Uploading (Multer) #### ❌ Bad Practice // Обработка потоков руками +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript @Post('upload') @@ -461,6 +515,8 @@ uploadFile(@UploadedFile() file: Express.Multer.File) {} ```typescript const { password, ...safeUser } = user; // Ручное удаление пароля ``` +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript class UserEntity { @Exclude() password: string; } @@ -474,6 +530,8 @@ class UserEntity { @Exclude() password: string; } ### 🚨 29. Fastify Integration #### ❌ Bad Practice // Вызов специфичных методов req.expressMethod +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript const app = await NestFactory.create(AppModule, new FastifyAdapter()); @@ -484,6 +542,8 @@ const app = await NestFactory.create(AppModule, new Fast ### 🚨 30. Shutdown Hooks (Graceful Shutdown) #### ❌ Bad Practice // Приложение убивается мгновенно, прерывая активные соединения +#### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. #### ✅ Best Practice ```typescript app.enableShutdownHooks(); @@ -493,8 +553,7 @@ app.enableShutdownHooks(); Вызывайте `enableShutdownHooks()`, чтобы отлавливать SIGINT/SIGTERM и безопасно завершать процессы базы данных. -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. + --- [⬆️ Back to Top](#) diff --git a/backend/nodejs/readme.md b/backend/nodejs/readme.md index 0462fdb..24e9840 100644 --- a/backend/nodejs/readme.md +++ b/backend/nodejs/readme.md @@ -48,6 +48,7 @@ graph TD class E layout; ``` --- + ## 1. ⚡ Blocking the Event Loop ### ❌ Bad Practice ```javascript @@ -57,6 +58,8 @@ app.post('/hash', (req, res) => { res.send(hash); }); ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const crypto = require('crypto'); @@ -70,14 +73,13 @@ app.post('/hash', (req, res, next) => { ### 🚀 Solution Never use synchronous methods (`*Sync`) on the main thread for crypto, I/O, or heavy calculations. Always use asynchronous callbacks or Promises to prevent blocking the Event Loop. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 2. 🗂️ Project Structure & Module Separation ### ❌ Bad Practice ```text /server.js (Contains routes, DB connections, and logic all in one 1500-line file) ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```text /src @@ -90,15 +92,14 @@ Insecure or unoptimized implementation that can cause performance bottlenecks, m ### 🚀 Solution Implement a multi-layered folder architecture. Strictly separate the HTTP transport layer (Routes/Controllers) from the Business Logic (Services) and Database operations. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 3. 🛡️ Strict Environment Configuration ### ❌ Bad Practice ```javascript const port = process.env.PORT || 3000; // Continuing application startup without validating required variables. ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const requiredEnv = ['DATABASE_URL', 'JWT_SECRET', 'PORT']; @@ -112,14 +113,13 @@ requiredEnv.forEach((name) => { ### 🚀 Solution Fail fast. Validate all necessary environment variables upon application startup to prevent fatal runtime errors later in execution. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 4. 🛑 Error Handling with Custom Classes ### ❌ Bad Practice ```javascript if (!user) throw new Error('User not found'); ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript class AppError extends Error { @@ -134,12 +134,11 @@ if (!user) throw new AppError('User not found', 404); ### 🚀 Solution Extend the built-in `Error` object to create custom operational errors. This allows your global error handler to safely log and return predictable HTTP status codes without crashing the application. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 5. 🎛️ Handling Uncaught Exceptions & Rejections ### ❌ Bad Practice // Ignoring process-level events, allowing the app to run in an unpredictable state after an error. +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript process.on('uncaughtException', (err) => { @@ -155,12 +154,11 @@ process.on('unhandledRejection', (err) => { ### 🚀 Solution Always capture `uncaughtException` and `unhandledRejection`. Log the fatal error immediately and shut down the process safely. Rely on a process manager (like PM2 or Kubernetes) to restart the container. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 6. 🔒 Hiding Sensitive Headers ### ❌ Bad Practice // Sending default headers that expose the framework, like `X-Powered-By: Express`. +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript // Example using Express + Helmet, but applies generically to HTTP responses @@ -170,12 +168,11 @@ app.use(helmet()); ### 🚀 Solution Sanitize outgoing HTTP headers to prevent information leakage about the server infrastructure. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 7. ⏱️ Implementing Graceful Shutdown ### ❌ Bad Practice // Application crashes abruptly during deployments, interrupting active user requests and corrupting database transactions. +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript process.on('SIGTERM', () => { @@ -192,15 +189,14 @@ process.on('SIGTERM', () => { ### 🚀 Solution Listen for termination signals (`SIGTERM`, `SIGINT`). Finish processing ongoing HTTP requests and safely close database connections before exiting the Node.js process. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 8. 🔍 Input Validation and Sanitization ### ❌ Bad Practice ```javascript // Blindly trusting user input const user = await db.query(`SELECT * FROM users WHERE email = '${req.body.email}'`); ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript // Utilizing parameterized queries and a validation library like Joi or Zod @@ -213,9 +209,6 @@ const user = await db.query('SELECT * FROM users WHERE email = $1', [value.email ### 🚀 Solution Never trust external data. Validate input strictly using schema definitions and always utilize parameterized queries or an ORM to prevent SQL/NoSQL Injection attacks. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 9. 🚀 Utilizing Worker Threads for Heavy Tasks ### ❌ Bad Practice ```javascript @@ -224,6 +217,8 @@ function processImage(buffer) { // heavy sync computation taking 500ms... } ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const { Worker } = require('worker_threads'); @@ -239,14 +234,13 @@ function processImageAsync(buffer) { ### 🚀 Solution Offload CPU-intensive operations (image processing, video encoding, heavy cryptographic tasks) to Node.js `worker_threads` to keep the primary event loop highly responsive for API requests. - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ## 10. 📝 Centralized and Structured Logging ### ❌ Bad Practice ```javascript console.log('User logged in', userId); ``` +### ⚠️ Problem +Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend. ### ✅ Best Practice ```javascript const winston = require('winston'); @@ -266,7 +260,3 @@ Avoid `console.log`. Use a sophisticated logging library (like Pino or Winston)
Enforce these Core Node.js constraints to ensure a highly scalable, stable, and performant backend system! 🟢
- - -### ⚠️ Problem -Insecure or unoptimized implementation that can cause performance bottlenecks, maintainability issues, or security vulnerabilities. It deviates from modern deterministic standards, making the code harder for AI Agents and Senior Developers to parse and safely extend.