npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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.

npm version License: ISC TypeScript


Table of Contents


Features

  • Standardized Error Architecture: All custom errors extend a base CustomError abstract 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-validator Integration: Pre-built validateRequest middleware to automatically handle validation result sets.
  • JWT Authentication Flow: Extract token claims effortlessly with currentUser and enforce route protection with requireAuth.
  • Fully Typed: Bundled TypeScript .d.ts declaration files and source maps for full IDE autocomplete and inline documentation.

Installation

Install via npm:

npm install @rachit-makes/reusable-components

Or using Yarn / pnpm:

yarn add @rachit-makes/reusable-components
# or
pnpm add @rachit-makes/reusable-components

Quick 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.


License

ISC