@rachit-makes/reusable-components
v1.0.9
Published
> A production-ready, TypeScript-first Node.js & Express utility library providing standardized HTTP error classes, central error-handling middleware, request validation helpers, and JWT authentication wrappers for microservices.
Downloads
555
Readme
@rachit-makes/reusable-components
A production-ready, TypeScript-first Node.js & Express utility library providing standardized HTTP error classes, central error-handling middleware, request validation helpers, and JWT authentication wrappers for microservices.
Table of Contents
Features
- Standardized Error Architecture: All custom errors extend a base
CustomErrorabstract class, ensuring every API error returns a uniform JSON response structure. - Express Global Error Handler: Middleware that automatically captures thrown errors and outputs predictable error arrays to clients.
express-validatorIntegration: Pre-builtvalidateRequestmiddleware to automatically handle validation result sets.- JWT Authentication Flow: Extract token claims effortlessly with
currentUserand enforce route protection withrequireAuth. - Fully Typed: Bundled TypeScript
.d.tsdeclaration files and source maps for full IDE autocomplete and inline documentation.
Installation
Install via npm:
npm install @rachit-makes/reusable-componentsOr using Yarn / pnpm:
yarn add @rachit-makes/reusable-components
# or
pnpm add @rachit-makes/reusable-componentsQuick Start
import express from 'express';
import {
errorHandler,
NotFoundError,
currentUser,
requireAuth
} from '@rachit-makes/reusable-components';
const app = express();
app.use(express.json());
// Extract user JWT payload if present
app.use(currentUser);
// Protected endpoint example
app.get('/api/users/profile', requireAuth, (req, res) => {
res.send({ user: req.currentUser });
});
// Wildcard 404 handler
app.all('*', async () => {
throw new NotFoundError();
});
// Register global error handler as the FINAL middleware
app.use(errorHandler);
app.listen(3000, () => console.log('Server running on port 3000'));Error Handling
Global Error Handler Middleware
Register errorHandler after all routes and controllers. It catches any thrown instance of CustomError and formats it into a uniform response:
app.use(errorHandler);Standardized JSON Response Format:
{
"errors": [
{
"message": "Not Found"
}
]
}If field-specific validation errors occur, field context is automatically attached:
{
"errors": [
{
"message": "Email must be valid",
"field": "email"
}
]
}Built-in Custom Error Classes
| Class | HTTP Status | Description | Example Usage |
| :--- | :--- | :--- | :--- |
| BadRequestError(message) | 400 | Generic bad request or invalid state | throw new BadRequestError('Invalid email'); |
| NotAuthorizedError() | 401 | Unauthenticated user access | throw new NotAuthorizedError(); |
| NotFoundError() | 404 | Requested route or entity not found | throw new NotFoundError(); |
| RequestValidationError(errors) | 400 | Wraps express-validator error arrays | Used inside validateRequest |
| DatabaseConnectionError() | 500 | Database connectivity failure | throw new DatabaseConnectionError(); |
Creating Custom Errors:
You can also extend CustomError to create domain-specific errors in your microservice:
import { CustomError } from '@rachit-makes/reusable-components';
export class PaymentRequiredError extends CustomError {
statusCode = 402;
constructor() {
super('Payment required to access this resource');
Object.setPrototypeOf(this, PaymentRequiredError.prototype);
}
serializeErrors() {
return [{ message: 'Payment required' }];
}
}Middlewares
Request Validation (validateRequest)
Use validateRequest alongside express-validator chains to automate error throwing when validation checks fail:
import express from 'express';
import { body } from 'express-validator';
import { validateRequest } from '@rachit-makes/reusable-components';
const router = express.Router();
router.post(
'/api/users/signup',
[
body('email').isEmail().withMessage('Email must be valid'),
body('password').trim().isLength({ min: 4, max: 20 }).withMessage('Password must be between 4 and 20 characters')
],
validateRequest,
async (req: express.Request, res: express.Response) => {
// Execution reaches here ONLY if validation passes
res.status(201).send({ success: true });
}
);Authentication (currentUser & requireAuth)
1. currentUser
Parses JWT tokens attached to session cookies or headers and assigns the decoded payload to req.currentUser.
import { currentUser } from '@rachit-makes/reusable-components';
app.use(currentUser);2. requireAuth
Enforces authentication on specific routes. If req.currentUser is undefined, it immediately throws a NotAuthorizedError (401).
import { requireAuth } from '@rachit-makes/reusable-components';
router.get('/api/orders', requireAuth, async (req, res) => {
// Guaranteed that req.currentUser exists
res.send({ userId: req.currentUser.id });
});TypeScript Support
This package is written in TypeScript and provides pre-compiled declaration files (.d.ts) and sourcemaps. No additional @types/ installation is required.
