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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@shifas7/response-handler

v1.0.1

Published

A TypeScript utility library for handling HTTP responses with standardized error handling and response formatting

Readme

Response Handler

npm version License: MIT TypeScript

A TypeScript utility library for handling HTTP responses with standardized error handling and response formatting. Perfect for Express.js applications that need consistent API response structures.

Features

  • 🚀 Type-safe - Full TypeScript support with comprehensive type definitions
  • 📦 Tree-shakable - Optimized exports for minimal bundle size
  • 🎯 Express.js ready - Built specifically for Express.js applications
  • 🔧 Standardized responses - Consistent API response format across your application
  • 🛡️ Error handling - Built-in error handling with automatic Prisma error mapping
  • 📄 Pagination support - Easy pagination metadata handling
  • 🎨 Customizable - Flexible message customization and metadata support
  • 📚 Well documented - Comprehensive JSDoc documentation

Installation

npm install @shifas7/response-handler
yarn add @shifas7/response-handler
pnpm add @shifas7/response-handler

Quick Start

import express from 'express';
import ResponseHandler from '@shifas7/response-handler';

const app = express();

// Success response
app.get('/users', (req, res) => {
  const users = [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }];
  ResponseHandler.success(res, users, 'Users retrieved successfully');
});

// Error response
app.get('/users/:id', (req, res) => {
  const user = null; // User not found
  if (!user) {
    return ResponseHandler.notFound(res, 'User not found');
  }
  ResponseHandler.success(res, user);
});

// Async handler with automatic error catching
app.get('/users/:id', ResponseHandler.asyncHandler(async (req, res) => {
  const user = await getUserById(req.params.id);
  ResponseHandler.success(res, user);
}));

API Reference

ResponseHandler Class

The main class providing static methods for sending standardized HTTP responses.

Methods

success<T>(res, data?, message?, statusCode?, meta?)

Send a success response with optional data and metadata.

Parameters:

  • res - Express Response object
  • data - Optional data payload (default: undefined)
  • message - Success message (default: "Operation completed successfully")
  • statusCode - HTTP status code (default: 200)
  • meta - Optional metadata object

Example:

ResponseHandler.success(res, { id: 1, name: 'John' });
ResponseHandler.success(res, userData, 'User profile updated', 200, { version: '1.0' });
error(res, message?, statusCode?, error?, data?)

Send an error response with optional error details.

Parameters:

  • res - Express Response object
  • message - Error message (default: "Internal server error")
  • statusCode - HTTP status code (default: 500)
  • error - Optional error details (string or object)
  • data - Optional data payload (useful for partial success scenarios)

Example:

ResponseHandler.error(res, 'Something went wrong', 500);
ResponseHandler.error(res, 'Validation failed', 400, { field: 'email', message: 'Invalid format' });
created<T>(res, data?, message?, meta?)

Send a created response (201) for successful resource creation.

Example:

ResponseHandler.created(res, newUser);
ResponseHandler.created(res, user, 'User account created successfully');
noContent(res)

Send a no content response (204) for successful operations with no data.

Example:

ResponseHandler.noContent(res); // After successful deletion
badRequest(res, message?, error?)

Send a bad request response (400) for invalid client requests.

Example:

ResponseHandler.badRequest(res);
ResponseHandler.badRequest(res, 'Invalid email format', { field: 'email' });
unauthorized(res, message?, error?)

Send an unauthorized response (401) for authentication failures.

Example:

ResponseHandler.unauthorized(res);
ResponseHandler.unauthorized(res, 'Invalid token');
forbidden(res, message?, error?)

Send a forbidden response (403) for authorization failures.

Example:

ResponseHandler.forbidden(res);
ResponseHandler.forbidden(res, 'Insufficient permissions');
notFound(res, message?, error?)

Send a not found response (404) for missing resources.

Example:

ResponseHandler.notFound(res);
ResponseHandler.notFound(res, 'User not found');
conflict(res, message?, error?)

Send a conflict response (409) for resource conflicts.

Example:

ResponseHandler.conflict(res);
ResponseHandler.conflict(res, 'Email already exists');
validationError(res, message?, error?)

Send a validation error response (422) for validation failures.

Example:

ResponseHandler.validationError(res);
ResponseHandler.validationError(res, 'Invalid input', {
  email: 'Invalid email format',
  password: 'Password too short'
});
internalError(res, message?, error?)

Send an internal server error response (500) for server errors.

Example:

ResponseHandler.internalError(res);
ResponseHandler.internalError(res, 'Database connection failed');
paginated<T>(res, data, pagination, message?)

Send a paginated response with pagination metadata.

Parameters:

  • res - Express Response object
  • data - Array of data items
  • pagination - Pagination information object with page, limit, and total
  • message - Success message (default: "Operation completed successfully")

Example:

ResponseHandler.paginated(res, users, { page: 1, limit: 10, total: 100 });
ResponseHandler.paginated(res, products, pagination, 'Products retrieved successfully');
asyncHandler(fn)

Async handler wrapper for Express route handlers to catch and handle errors automatically.

Features:

  • Automatically handles Prisma errors (P2002, P2025)
  • Handles validation errors
  • Provides development vs production error details

Example:

app.get('/users', ResponseHandler.asyncHandler(async (req, res) => {
  const users = await User.findMany();
  ResponseHandler.success(res, users);
}));

app.get('/users/:id', ResponseHandler.asyncHandler(userController.getById));

Response Interface

ApiResponse<T>

Standard API response interface for consistent response formatting.

interface ApiResponse<T = any> {
  success: boolean;
  message: string;
  data?: T;
  error?: string | object;
  statusCode: number;
  timestamp: string;
  meta?: {
    pagination?: {
      page: number;
      limit: number;
      total: number;
      totalPages: number;
    };
    [key: string]: any;
  };
}

HTTP Status Codes

HttpStatusCode

Enum containing common HTTP status codes for consistent usage.

enum HttpStatusCode {
  OK = 200,
  CREATED = 201,
  NO_CONTENT = 204,
  BAD_REQUEST = 400,
  UNAUTHORIZED = 401,
  FORBIDDEN = 403,
  NOT_FOUND = 404,
  CONFLICT = 409,
  UNPROCESSABLE_ENTITY = 422,
  INTERNAL_SERVER_ERROR = 500,
  BAD_GATEWAY = 502,
  SERVICE_UNAVAILABLE = 503,
}

Response Messages

ResponseMessages(message?)

Factory function to generate common response messages with optional customization.

Example:

const messages = ResponseMessages('User');
// messages.CREATED = "User created successfully"

const defaultMessages = ResponseMessages();
// defaultMessages.SUCCESS = "Operation completed successfully"

Advanced Usage

Custom Response Messages

import { ResponseMessages } from '@shifas7/response-handler';

const userMessages = ResponseMessages('User');
ResponseHandler.success(res, user, userMessages.CREATED);

Error Handling with Prisma

The asyncHandler automatically maps common Prisma errors:

app.post('/users', ResponseHandler.asyncHandler(async (req, res) => {
  const user = await prisma.user.create({
    data: req.body
  });
  ResponseHandler.created(res, user);
}));
// P2002 (unique constraint violation) → 409 Conflict
// P2025 (record not found) → 404 Not Found

Pagination Example

app.get('/users', ResponseHandler.asyncHandler(async (req, res) => {
  const page = parseInt(req.query.page as string) || 1;
  const limit = parseInt(req.query.limit as string) || 10;
  const skip = (page - 1) * limit;

  const [users, total] = await Promise.all([
    prisma.user.findMany({ skip, take: limit }),
    prisma.user.count()
  ]);

  ResponseHandler.paginated(res, users, { page, limit, total });
}));

Custom Metadata

ResponseHandler.success(res, data, 'Data retrieved', 200, {
  version: '1.0',
  cache: 'miss',
  processingTime: '150ms'
});

Response Format

All responses follow this standardized format:

Success Response

{
  "success": true,
  "message": "Operation completed successfully",
  "data": { "id": 1, "name": "John" },
  "statusCode": 200,
  "timestamp": "2024-01-15T10:30:00.000Z",
  "meta": {
    "pagination": {
      "page": 1,
      "limit": 10,
      "total": 100,
      "totalPages": 10
    }
  }
}

Error Response

{
  "success": false,
  "message": "User not found",
  "error": "User with ID 123 does not exist",
  "statusCode": 404,
  "timestamp": "2024-01-15T10:30:00.000Z"
}

TypeScript Support

This library is written in TypeScript and provides full type definitions. Import types as needed:

import ResponseHandler, { 
  ApiResponse, 
  HttpStatusCode, 
  ResponseMessages 
} from '@shifas7/response-handler';

// Type your responses
const response: ApiResponse<User[]> = {
  success: true,
  message: 'Users retrieved',
  data: users,
  statusCode: HttpStatusCode.OK,
  timestamp: new Date().toISOString()
};

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Changelog

1.0.0

  • Initial release
  • Complete TypeScript support
  • Express.js integration
  • Standardized response format
  • Error handling utilities
  • Pagination support
  • Async handler wrapper