
Security News
Axios Supply Chain Attack Reaches OpenAI macOS Signing Pipeline, Forces Certificate Rotation
OpenAI rotated macOS signing certificates after a malicious Axios package reached its CI pipeline in a broader software supply chain attack.
apienvelope
Advanced tools
Production-grade npm package for standardized API response formatting in Express applications
Standardized API response formatting for Express.js applications. Enforces consistent response structures, handles errors gracefully, and provides built-in pagination support with full TypeScript coverage.
Building REST APIs often leads to inconsistent response formats across endpoints. This package solves that by providing:
npm install apienvelope
import express from 'express';
import { responseWrapper, errorCatcher, NotFoundError } from 'apienvelope';
const app = express();
app.use(responseWrapper({ environment: 'production' }));
app.get('/users/:id', async (req, res) => {
const user = await db.users.findById(req.params.id);
if (!user) {
throw new NotFoundError('User not found');
}
res.respond(user);
});
app.get('/posts', async (req, res) => {
const { page = 1, limit = 10 } = req.query;
const { data, total } = await db.posts.paginate(page, limit);
res.respondPaginated(data, { page: Number(page), limit: Number(limit), total });
});
app.use(errorCatcher({ environment: 'production' }));
app.listen(3000);
{
"success": true,
"data": { "id": 1, "name": "John Doe", "email": "john@example.com" },
"meta": { "requestId": "req_abc123" },
"timestamp": "2024-12-23T10:30:00.000Z"
}
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Validation failed",
"fields": {
"email": ["Invalid email format"],
"password": ["Must be at least 8 characters"]
}
},
"meta": { "requestId": "req_abc123" },
"timestamp": "2024-12-23T10:30:00.000Z"
}
{
"success": true,
"data": [{ "id": 1, "title": "Post 1" }, { "id": 2, "title": "Post 2" }],
"pagination": {
"page": 1,
"limit": 10,
"total": 100,
"totalPages": 10,
"hasNextPage": true,
"hasPreviousPage": false
},
"timestamp": "2024-12-23T10:30:00.000Z"
}
| Class | Status | Code |
|---|---|---|
ValidationError | 400 | VALIDATION_ERROR |
BadRequestError | 400 | BAD_REQUEST |
UnauthorizedError | 401 | UNAUTHORIZED |
ForbiddenError | 403 | FORBIDDEN |
NotFoundError | 404 | NOT_FOUND |
ConflictError | 409 | CONFLICT |
UnprocessableEntityError | 422 | UNPROCESSABLE_ENTITY |
RateLimitError | 429 | RATE_LIMIT_EXCEEDED |
InternalServerError | 500 | INTERNAL_ERROR |
ServiceUnavailableError | 503 | SERVICE_UNAVAILABLE |
app.use(responseWrapper({
environment: 'production',
includeStackTraces: false,
requestIdHeader: 'x-request-id',
correlationIdHeader: 'x-correlation-id',
generateRequestId: true,
maskSensitiveData: true,
sensitiveFields: ['password', 'token', 'secret', 'apiKey'],
pagination: {
defaultLimit: 20,
maxLimit: 100,
includeLinks: true,
},
customErrorMappers: new Map([
[PaymentError, 402],
[RateLimitError, 429],
]),
}));
Full generic support for type-safe API responses:
import { ApiResponse, isSuccessResponse } from 'apienvelope';
interface User {
id: number;
name: string;
}
async function getUser(id: number): Promise<User | null> {
const response: ApiResponse<User> = await fetch(`/api/users/${id}`).then(r => r.json());
if (isSuccessResponse(response)) {
return response.data; // TypeScript infers User type
}
return null;
}
Extend ApiError for domain-specific errors:
import { ApiError } from 'apienvelope';
class InsufficientFundsError extends ApiError {
constructor(balance: number, required: number) {
super('Insufficient funds for this transaction', {
code: 'INSUFFICIENT_FUNDS',
statusCode: 402,
details: { currentBalance: balance, requiredAmount: required },
});
}
}
Wrap async routes to automatically catch and forward errors:
import { asyncHandler } from 'apienvelope';
app.get('/users/:id', asyncHandler(async (req, res) => {
const user = await db.users.findById(req.params.id);
res.respond(user);
}));
Utility class for handling pagination logic:
import { PaginationHelper } from 'apienvelope';
const paginator = new PaginationHelper({ defaultLimit: 20, maxLimit: 100 });
app.get('/items', async (req, res) => {
const { page, limit } = paginator.extractFromRequest(req);
const offset = paginator.calculateOffset(page, limit);
const items = await db.items.find().skip(offset).limit(limit);
const total = await db.items.count();
res.respondPaginated(items, { page, limit, total });
});
Support for cursor-based pagination:
app.get('/feed', async (req, res) => {
const { cursor, limit = 20 } = req.query;
const { items, nextCursor } = await db.feed.getCursor(cursor, limit);
res.respondCursorPaginated(items, {
limit: Number(limit),
cursor: cursor as string,
nextCursor,
hasMore: !!nextCursor,
});
});
Transform responses before they're sent:
app.use(responseWrapper({
preResponseHooks: [
(data, meta) => ({
data,
meta: { ...meta, apiVersion: '2.0' },
}),
],
postResponseHooks: [
(response) => ({
...response,
meta: { ...response.meta, serverTime: Date.now() },
}),
],
}));
responseWrapper(options) - Adds response formatting methods to ExpresserrorCatcher(options) - Global error handler middlewareasyncHandler(fn) - Wraps async functions for error handlingres.respond(data, meta?, statusCode?) - Send formatted success responseres.respondPaginated(data, pagination, meta?) - Send paginated responseres.respondCursorPaginated(data, pagination, meta?) - Send cursor-paginated responseres.respondError(error, meta?) - Send formatted error responseResponseFormatter - Core formatting logicPaginationHelper - Pagination utilitiesApiError - Base error classStatusCodeMapper - HTTP status code mappingisSuccessResponse(response) - Check if response is successfulisErrorResponse(response) - Check if response is an errorisPaginatedResponse(response) - Check if response is paginatedSepehr Mohseni
MIT
FAQs
Production-grade npm package for standardized API response formatting in Express applications
We found that apienvelope 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
OpenAI rotated macOS signing certificates after a malicious Axios package reached its CI pipeline in a broader software supply chain attack.

Security News
Open source is under attack because of how much value it creates. It has been the foundation of every major software innovation for the last three decades. This is not the time to walk away from it.

Security News
Socket CEO Feross Aboukhadijeh breaks down how North Korea hijacked Axios and what it means for the future of software supply chain security.