@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.
What problem it solves
Building consistent, robust APIs requires boilerplate code for:
- Standardizing API responses (success vs. error payloads).
- Handling async errors without
try-catchblocks 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-kitRequirements:
- 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 ExpressRequest,Response, andNextFunction.
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.
