Standardized API response and error handling toolkit with async handler, requestId, logging, and configurable formats.
npm install api-stds
successResponse, errorResponse)
asyncHandler wrapper for safe async/await route handling
ApiError class for consistent error throwing
standardize) to attach res.success and res.error methods
bash
npx api-stds init
``
This will set up the package in your project.
---
Usage
$3
`ts
import express from "express";
import { standardize } from "api-stds";
const app = express();
// Apply standardize middleware
app.use(standardize());
`
This middleware extends the res object with:
`ts
res.success(data, meta?);
res.error(code, message?, details?, meta?);
`
---
$3
`ts
app.get("/ping", (req, res) => {
return res.success({ pong: true });
});
`
Response:
`json
{
"success": true,
"data": { "pong": true },
"error": null,
"meta": {
"timestamp": 1734913293044,
"apiVersion": "v1"
}
}
`
---
$3
`ts
app.get("/error", (req, res) => {
return res.error("NOT_FOUND", "Resource not found", { resource: "User" });
});
`
Response:
`json
{
"success": false,
"data": null,
"error": {
"code": "NOT_FOUND",
"message": "Resource not found",
"details": { "resource": "User" }
},
"meta": {
"timestamp": 1734913293044,
"apiVersion": "v1"
}
}
`
---
$3
`ts
import { asyncHandler, ApiError } from "api-stds";
app.get(
"/users/:id",
asyncHandler(async (req, res) => {
const user = await User.findById(req.params.id);
if (!user) throw new ApiError("NOT_FOUND", "User not found");
return res.success(user);
})
);
`
---
$3
`ts
import { ApiError } from "api-stds";
throw new ApiError("BAD_REQUEST", "Invalid input", [
{ field: "email", message: "Email is required" },
]);
`
---
$3
`ts
app.use(
standardize({
response: {
includeMeta: true,
timestampFormat: "iso", // "unix" | "iso"
defaultApiVersion: "v2",
metaFields: ["timestamp", "apiVersion"],
},
})
);
`
---
$3
`ts
import { loadErrorRegistry, getError } from "api-stds";
loadErrorRegistry({
NOT_FOUND: "The resource was not found",
UNAUTHORIZED: "Unauthorized access",
});
res.error("NOT_FOUND", getError("NOT_FOUND"));
`
---
Response Format
``json