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

@ashutoshm/node-api-kit

v1.0.0

Published

A production ready api response formatter and error handler with centralized error middleware

Readme

@ashutoshm/node-api-kit

A production-ready API response formatter and centralized error handler for Node.js and Express applications.

npm version License: ISC

What problem it solves

Building consistent, robust APIs requires boilerplate code for:

  • Standardizing API responses (success vs. error payloads).
  • Handling async errors without try-catch blocks everywhere.
  • centralized error handling (differentiating between operational errors like validation issues and programming bugs).

node-api-kit provides a lightweight, type-safe set of utilities to handle these concerns out of the box, ensuring your API behaves predictably and consistently.

Note: Currently, this package provides core utilities and Express.js integration. The core logic is decoupled and can be extended to support other frameworks like NestJS, Fastify, or vanilla Node.js servers in the future.

Installation

npm install @ashutoshm/node-api-kit

Requirements:

  • Node.js >= 18.0.0

Basic Usage

The package exports both core utilities and Express-specific helpers.

import { ApiError } from '@ashutoshm/node-api-kit';

// Create a predictable operational error
const error = new ApiError(404, 'User not found');

Express Integration

Integrate cleanly with your Express application using the provided middleware and helpers.

import express from 'express';
import { 
  sendSuccess, 
  asyncHandler, 
  errorMiddleware 
} from '@ashutoshm/node-api-kit/express';

const app = express();

app.use(express.json());

// ... routes go here ...

// Register the centralized error handler at the end
app.use(errorMiddleware);

app.listen(3000);

Sending Success Responses

Use sendSuccess to return consistent JSON payloads.

app.get('/users', asyncHandler(async (req, res) => {
  const users = [{ id: 1, name: 'Alice' }];
  
  // Returns 200 OK
  return sendSuccess(res, users);
}));

app.post('/users', asyncHandler(async (req, res) => {
  const newUser = { id: 2, name: 'Bob' };
  
  // Custom status code and message
  return sendSuccess(res, newUser, {
    statusCode: 201,
    message: 'User created successfully',
    meta: { version: '1.0' }
  });
}));

Response Format:

{
  "success": true,
  "message": "User created successfully",
  "data": { "id": 2, "name": "Bob" },
  "meta": { "version": "1.0" }
}

Error Handling Examples

Operational Errors

Throw ApiError for expected errors (e.g., validation failure, not found, forbidden).

import { ApiError } from '@ashutoshm/node-api-kit';

app.get('/protected', asyncHandler(async (req, res) => {
  const hasAccess = false;
  
  if (!hasAccess) {
    throw new ApiError(403, 'Access Denied', { 
      code: 'FORBIDDEN_ACCESS' 
    });
  }
}));

Response:

{
  "success": false,
  "message": "Access Denied"
}

Validation Errors

Pass detailed error objects when validation fails.

throw new ApiError(422, 'Validation Failed', {
  errors: [
    { field: 'email', message: 'Invalid email format' }
  ]
});

Response:

{
  "success": false,
  "message": "Validation Failed",
  "errors": [
    { "field": "email", "message": "Invalid email format" }
  ]
}

Unexpected Errors

Any unhandled exception (like a database connection failure or TypeError) is automatically caught by asyncHandler, passed to errorMiddleware, and masked as a generic 500 error to prevent leaking internal details.

app.get('/crash', asyncHandler(async () => {
  throw new Error('Database disconnected'); // or throw "Some string"
}));

Response:

{
  "success": false,
  "message": "Internal Server Error"
}

TypeScript Support

This package is written in TypeScript and ships with built-in type definitions.

  • ApiError: Typed class for errors.
  • ApiResponse: Interfaces for success and error response structures.
  • Middleware: Compatible with Express Request, Response, and NextFunction.

Configuration Options

ApiError

| Option | Type | Default | Description | |---|---|---|---| | code | string | 'INTERNAL_SERVER_ERROR' | A machine-readable error code. | | errors | any | null | Detailed error info (e.g., validation arrays). | | isOperational | boolean | true | If false, the error is treated as a systemic failure (500). |

Roadmap

  • [ ] Add support for independent core logic to support other frameworks (NestJS, Fastify).
  • [ ] Add support for Zod validation middleware.
  • [ ] Add customizable logger integration (e.g., Winston, Pino).
  • [ ] Add Request ID tracking support.