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

standard-api-response-handler

v1.0.1

Published

A lightweight and standard API response handler for Node.js and Express.

Readme

🚀 API Response Handler

A lightweight, highly robust, and standardized API response handler for Node.js and Express applications. It effortlessly guarantees a clean, consistent, and predictable response structure across your entire API architecture.


✨ Features

  • 💎 Standardized Format: Uniform success, error, and paginated responses.
  • Lightweight & Fast: Zero external runtime dependencies.
  • 📈 Smart Pagination: Built-in calculation for pages, limits, total items, and next/prev status indicators.
  • 🛡️ TypeScript Ready: Full type definitions out of the box with IApiResponse.
  • 🎛️ Extremely Flexible: Custom metadata and dynamic error payloads supported.

⚙️ Requirements

  • Runtime: Node.js >= 12.0.0 (Works in almost any modern Node environment)
  • Development & Testing: Node.js >= 18.0.0 (Required for the native node:test suite)

📦 Installation

Install the package via your favorite package manager:

# Using npm
npm install standard-api-response-handler

# Using yarn
yarn add standard-api-response-handler

# Using pnpm
pnpm add standard-api-response-handler

🛠️ Quick Start & Usage

1. Standard Success Response

Quickly send successful responses with data, optional custom messages, and custom HTTP status codes (defaults to 200).

const ApiResponse = require('standard-api-response-handler').default;

app.get('/api/users/:id', async (req, res) => {
  const user = { id: 42, username: 'dev_hero' };
  
  // Sends a standard 200 OK response
  return ApiResponse.success(res, user, 'User profile fetched successfully');
});

Response Payload:

{
  "success": true,
  "status": 200,
  "message": "User profile fetched successfully",
  "data": {
    "id": 42,
    "username": "dev_hero"
  }
}

2. Robust Error Response

Consistently catch and format error responses. Supports custom HTTP status codes (defaults to 500) and optional validation/error payload arrays.

const ApiResponse = require('standard-api-response-handler').default;

app.post('/api/register', (req, res) => {
  const errors = { email: 'Email address is invalid' };
  
  // Sends a standard 400 Bad Request with details
  return ApiResponse.error(res, 'Validation failed', 400, errors);
});

Response Payload:

{
  "success": false,
  "status": 400,
  "message": "Validation failed",
  "errors": {
    "email": "Email address is invalid"
  }
}

3. Smart Paginated Response

Pass your raw data array and pagination metrics, and let the handler auto-calculate all structural parameters (total pages, current page, limits, and next/prev page flags).

const ApiResponse = require('standard-api-response-handler').default;

app.get('/api/products', async (req, res) => {
  const page = parseInt(req.query.page) || 1;
  const limit = parseInt(req.query.limit) || 10;
  
  const { products, totalCount } = await db.products.findAndCount({ page, limit });
  
  // Auto-calculates metadata and sends pagination
  return ApiResponse.paginate(res, products, page, limit, totalCount, 'Products retrieved successfully');
});

Response Payload:

{
  "success": true,
  "status": 200,
  "message": "Products retrieved successfully",
  "data": [
    { "id": 1, "name": "Premium Keyboard" },
    { "id": 2, "name": "Ergonomic Mouse" }
  ],
  "meta": {
    "currentPage": 1,
    "itemsPerPage": 10,
    "totalItems": 45,
    "totalPages": 5,
    "hasNextPage": true,
    "hasPrevPage": false
  }
}

4. 🦕 TypeScript Usage

Fully compatible with TypeScript projects out-of-the-box. Import the helper class and leverage standard typings.

import ApiResponse, { IApiResponse } from 'standard-api-response-handler';
import { Request, Response } from 'express';

interface User {
  id: number;
  email: string;
}

export const getUserProfile = (req: Request, res: Response) => {
  const user: User = { id: 1, email: '[email protected]' };
  
  // Fully typed method signatures
  return ApiResponse.success(res, user, 'Profile loaded');
};

📖 API Reference

ApiResponse.success(res, data, message, statusCode, meta)

| Parameter | Type | Required | Default | Description | | :--- | :--- | :---: | :---: | :--- | | res | Response | Yes | — | Express-like Response Object | | data | any | No | null | The actual payload data to return | | message | string | No | 'Success' | User-friendly message for feedback | | statusCode | number | No | 200 | HTTP Status Code to return | | meta | any | No | null | Optional custom metadata object |

ApiResponse.error(res, message, statusCode, errors)

| Parameter | Type | Required | Default | Description | | :--- | :--- | :---: | :---: | :--- | | res | Response | Yes | — | Express-like Response Object | | message | string | No | 'Internal Server Error' | Human-readable error description | | statusCode | number | No | 500 | HTTP Status Code to return | | errors | any | No | null | Detailed validation errors or system debug errors |

ApiResponse.paginate(res, data, page, limit, totalItems, message)

| Parameter | Type | Required | Default | Description | | :--- | :--- | :---: | :---: | :--- | | res | Response | Yes | — | Express-like Response Object | | data | any[] | Yes | — | Array of items for the current page | | page | number | Yes | — | Active page index (1-based) | | limit | number | Yes | — | Number of items per page | | totalItems | number | Yes | — | Total item count matching the query in database | | message | string | No | 'Data retrieved successfully' | Summary success description |


🪪 License

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