NexGenStudioDev/FastKit

Add Common Middleware Support (Validation, CORS, Logging, Error Handler, etc.)

Ouverte

#18 ouverte le 28 juin 2025

 (0 commentaire) (0 réaction) (0 personne assignée)TypeScript (0 fork)auto 404
backendenhancementgood first issuehelp wantednpmquestion

Métriques du dépôt

Stars
 (1 étoile)
Métriques de merge PR
 (Métriques PR en attente)

Description

📖 Description

Set up a robust collection of universal middleware functions that are reusable across all modules in a FastKit-style app. These middlewares should be plug-and-play, support TypeScript, and be easy to extend or replace.

This includes:

  • 🧪 Validation (validateBody, validateParams, validateQuery)

  • 🌐 CORS

  • 📄 Request logging

  • ❌ Global error handler

  • 🧼 Input sanitization

  • 🔄 Rate limiting

  • 🔎 NotFound handler

🧠 Why This Is Important

  • Standardizes request processing across all modules

  • Prevents repetitive boilerplate code in every controller

  • Helps debug and secure your app properly

  • Encourages good architecture and scalable structure

  • Every professional Express app needs these

##. 🧱 Folder Structure

src/
└── middlewares/
    │  
    ├── common/
    │   ├── validateBody.ts
    │   ├── validateParams.ts
    │   ├── validateQuery.ts
    │   ├── sanitizeInput.ts
    │   ├── cors.ts
    │   ├── requestLogger.ts
    │   ├── rateLimiter.ts
    │   ├── errorHandler.ts
    │   └── notFoundHandler.ts


✅ Tasks

🔐 Auth Middlewares

  • verifyToken: Decode JWT, attach authId

  • allowRoles('admin'): Role-based access control

🧪 Validation Middlewares

  • validateBody(schema): Validate req.body with Zod or Joi

  • validateParams(schema): Validate route params

  • validateQuery(schema): Validate query strings

  • sanitizeInput: Remove harmful tags/scripts

🌐 System-Level Middlewares

  • cors.ts: Setup CORS with whitelist

  • requestLogger.ts: Logs method, path, status, duration

  • rateLimiter.ts: Prevent abuse (optional, with express-rate-limit)

  • notFoundHandler.ts: Catch unknown routes

  • errorHandler.ts: Catch & respond with formatted error

##✨ Usage Example

// file.route.ts

router.post(
  '/files',
  validateBody(createFileSchema),
  sanitizeInput,
  fileController.create
);

// app.ts or main.ts

app.use(corsMiddleware);
app.use(requestLogger);
app.use(express.json());
app.use(rateLimiter);
app.use('/api/v1', mainRouter);
app.use(notFoundHandler);
app.use(errorHandler);

🚀 Expected Outcome

  • 🔄 All requests validated, sanitized, and logged

  • 🔐 Unauthorized access blocked cleanly

  • ❌ Invalid routes handled with friendly error

  • 💥 All errors go through one handler

  • 🔒 Easy to reuse in microservices or monorepos

🧠 Bonus Suggestions

  • ✅ Auto add API version headers (X-API-Version)

  • ⏱ Log response time using morgan or custom logger

  • 🧪 Add test coverage for each middleware

  • 📦 Export as reusable NPM package

Guide contributeur