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

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. Created Response (201)

Quickly send standard 201 Created responses when a new resource is successfully created.

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

app.post('/api/users', async (req, res) => {
  const newUser = { id: 43, username: 'new_coder' };
  
  // Sends a standard 201 Created response
  return ApiResponse.created(res, newUser, 'User created successfully');
});

Response Payload:

{
  "success": true,
  "status": 201,
  "message": "User created successfully",
  "data": {
    "id": 43,
    "username": "new_coder"
  }
}

4. Not Found Response (404)

Quickly send standard 404 Not Found responses when a requested resource is not found.

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

app.get('/api/users/:id', async (req, res) => {
  // If user is not found in database
  return ApiResponse.notFound(res, 'User not found');
});

Response Payload:

{
  "success": false,
  "status": 404,
  "message": "User not found"
}

5. 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
  }
}

6. 🦕 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 |


💡 Specialized Status Code Helper Methods

For cleaner, more semantic code, the library provides helper methods for common HTTP status codes.

Success Responses (2xx)

  • ApiResponse.created(res, data, message, meta) (201 Created)
  • ApiResponse.accepted(res, data, message, meta) (202 Accepted)
  • ApiResponse.noContent(res) (204 No Content - returns no response body)

Usage Example:

// Send a 201 Created response
ApiResponse.created(res, { id: 42 }, 'Resource created successfully');

// Send a 204 No Content response
ApiResponse.noContent(res);

Client Error Responses (4xx)

  • ApiResponse.badRequest(res, message, errors) (400 Bad Request)
  • ApiResponse.unauthorized(res, message, errors) (401 Unauthorized)
  • ApiResponse.forbidden(res, message, errors) (403 Forbidden)
  • ApiResponse.notFound(res, message, errors) (404 Not Found)
  • ApiResponse.methodNotAllowed(res, message, errors) (405 Method Not Allowed)
  • ApiResponse.conflict(res, message, errors) (409 Conflict)
  • ApiResponse.unprocessableEntity(res, message, errors) (422 Unprocessable Entity)
  • ApiResponse.tooManyRequests(res, message, errors) (429 Too Many Requests)

Usage Example:

// Send a 403 Forbidden response
ApiResponse.forbidden(res, 'You do not have access to this resource');

// Send a 422 Unprocessable Entity response with details
ApiResponse.unprocessableEntity(res, 'Validation failed', { email: 'Email already exists' });

Server Error Responses (5xx)

  • ApiResponse.internalServerError(res, message, errors) (500 Internal Server Error)
  • ApiResponse.notImplemented(res, message, errors) (501 Not Implemented)
  • ApiResponse.badGateway(res, message, errors) (502 Bad Gateway)
  • ApiResponse.serviceUnavailable(res, message, errors) (503 Service Unavailable)
  • ApiResponse.gatewayTimeout(res, message, errors) (504 Gateway Timeout)

Usage Example:

// Send a 503 Service Unavailable response
ApiResponse.serviceUnavailable(res, 'Database connection lost', databaseError);

🪪 License

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