
Security News
Attackers Are Hunting High-Impact Node.js Maintainers in a Coordinated Social Engineering Campaign
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.
node-js-api-response-ts
Advanced tools
Unified API response and error handling for Express.js in TypeScript. This package provides a middleware for consistent API responses and error handling in Express applications, making it easier to manage API responses and errors in a standardized way.
This package provides custom API response and error-handling middleware for Express.js applications. It helps standardize error handling, API responses, and logging based on the environment.
ApiError classApiResponse classerrorHandler) for consistent error responsesasyncHandler to catch unhandled promise rejectionsTo install the package:
npm install node-js-api-response-ts
OR
yarn add node-js-api-response-ts
asyncHandler for Express.jsasyncHandler is a utility function that helps manage asynchronous route handlers in Express.js applications. It automatically catches any errors and forwards them to the next middleware function, simplifying error handling for async code.
try-catch blocks for each route.The asyncHandler function is predefined as follows:
import { Request, Response, NextFunction } from 'express';
export const asyncHandler = (fn: (req: Request, res: Response, next: NextFunction) => Promise<any>) => {
return (req: Request, res: Response, next: NextFunction) => {
Promise.resolve(fn(req: Request, res: Response, next: NextFunction)).catch((err) => next(err));
}
}
asyncHandler wraps asynchronous route handlers in Express.js to ensure errors are forwarded to the error-handling middleware.
import express, { Application, NextFunction, Request, Response } from "express";
import { asyncHandler } from 'node-js-api-response-ts'; // Install via npm package
const app: Application = express();
// A sample asynchronous route using asyncHandler
app.get('/async-route', asyncHandler(async (req: Request, res: Response, next: NextFunction) => {
// Simulating async operation, e.g., fetching data from a database
const data = await fetchDataFromDatabase(); // Placeholder for async code
res.json(data); // Send data as JSON response
}));
// Default route to test
app.get('/', (req: Request, res: Response, next: NextFunction) => {
res.send('Welcome to the API!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
export default app;
The ApiResponse class and SuccessResponse function help standardize successful API responses in your Express.js application. They ensure that all successful responses follow a consistent structure, making your API easier to maintain and more predictable for clients.
statusCode, message, data, and status properties in the response.You can use ApiResponse and SuccessResponse to send structured, consistent responses.
new ApiResponse(...): You manually send the response.
SuccessResponse(...): Utility that handles res.status().json(...) internally.
import { ApiResponse, SuccessResponse } from 'node-js-api-response-ts';
app.get('/api/v1/success', (req: Request, res: Response, next: NextFunction) => {
// Data to return in the response
const data = {
user: { name: 'John Doe', age: 30 },
};
// Send a success response
// Option 1: Use ApiResponse class
//res.status(200).json(new ApiResponse(200, data, "Request successful"));
// Option 2: Use SuccessResponse utility function
return SuccessResponse(res, 200, data, 'Request successful');
});
Result:
{
"statusCode": 200,
"status": true,
"message": "Request successful",
"data": {
"user": { "name": "John Doe", "age": 30 }
}
}
errorHandler MiddlewareThe errorHandler middleware for Express.js is a custom middleware designed to handle errors in a centralized way. It formats the error response and logs the details based on the environment (development or production). This ensures that errors are properly handled and logged, while providing clients with a consistent error response format.
statusCode, message, status, and name.ApiError or any other error class.NODE_ENV environment variable.Ensure that the required dependencies (ApiError) are imported correctly into your application.
You can use the errorHandler middleware in your Express.js application to handle errors uniformly across your routes.
import { errorHandler, } from 'node-js-api-response-ts';
// Use the error handler middleware at last
app.use(errorHandler); // Place this after all routes
export default app;
It catches all thrown or passed errors and sends a structured response:
{
"status": false,
"statusCode": 400,
"message": "This is a test error"
}
The ApiError class and ErrorResponse function help handle errors in your Express.js application in a consistent and structured manner. These utilities are designed to make it easier to manage error responses, especially when dealing with asynchronous code and middleware.
ApiError Class: A custom error class that extends the built-in Error class to represent API errors with an HTTP status code and message.ErrorResponse Function: A utility function that creates an ApiError instance and passes it to the next middleware or throws an error if no next function is provided.You can use ApiError and ErrorResponse in your Express.js application to handle errors consistently.
ApiError: manually create and pass to next()
ErrorResponse: utility that does it for you
Use one or the other, not both
import { ApiError, ErrorResponse } from 'node-js-api-response-ts';
// A sample route that throws an error
app.get('/api/v1/error', (req: Request, res: Response, next: NextFunction) => {
// Trigger an API error response with a 400 status code
// Option 1: Use ApiResponse class
// next(new ApiError(400, 'Bad request: this is a test error'))
// Option 2: Use Use ErrorResponse helper function
return ErrorResponse(400, 'Bad request: this is a test error', next);
});
// Example route to simulate an internal server error
app.get('/api/v1/server-error', (req: Request, res: Response, next: NextFunction) => {
// Trigger a 500 error for internal server problems
return ErrorResponse(500, 'Internal server error occurred', next);
});
Result:
In production Response looks like
{
"statusCode": 400,
"status": false,
"message": "Bad request: this is a test error",
}
{
"statusCode": 500,
"status": false,
"message": "Internal server error occurred",
}
Includes stack trace:
{
"statusCode": 400,
"status": false,
"message": "Bad request: this is a test error",
"name": "ApiError",
"stack": "ApiError: Bad request: this is a test error at ErrorResponse (D:\WorkSpace\Node.js\typescript\src\utils\ApiError.ts:21:19) at D:\WorkSpace\Node.js\typescript\src\app.ts:32:25 at Layer.handle [as handle_request] (D:\WorkSpace\Node.js\typescript\node_modules\express\lib\router\layer.js:95:5) at next (D:\WorkSpace\Node.js\typescript\node_modules\express\lib\router\index.js:280:10) at cors (D:\WorkSpace\Node.js\typescript\node_modules\cors\lib\index.js:188:7)"
}
{
"statusCode": 500,
"status": false,
"message": "Internal server error occurred",
"name": "ApiError",
"stack": "ApiError: Internal server error occurred at ErrorResponse (D:\WorkSpace\Node.js\typescript\src\utils\ApiError.ts:21:19) at D:\WorkSpace\Node.js\typescript\src\app.ts:32:25 at Layer.handle [as handle_request] (D:\WorkSpace\Node.js\typescript\node_modules\express\lib\router\layer.js:95:5) at next (D:\WorkSpace\Node.js\typescript\node_modules\express\lib\router\index.js:280:10) at cors (D:\WorkSpace\Node.js\typescript\node_modules\cors\lib\index.js:188:7)"
}
SuccessResponse(res, statusCode, data, message?)ErrorResponse(statusCode, message, next)ApiErrorstatusCode and statusasyncHandler(fn)errorHandlerThis package is licensed under the MIT License.
This documentation provides a quick overview of the features, installation instructions, and usage examples for each utility. Let me know if you need further clarifications!
FAQs
Unified API response and error handling for Express.js in TypeScript. This package provides a middleware for consistent API responses and error handling in Express applications, making it easier to manage API responses and errors in a standardized way.
We found that node-js-api-response-ts demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.

Security News
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.

Security News
Node.js has paused its bug bounty program after funding ended, removing payouts for vulnerability reports but keeping its security process unchanged.