JSend Middleware is a lightweight utility for Express.js applications that implements the JSend specification to standardize JSON API responses. It provides a simple, consistent way to send success, fail, and error responses with customizable status labels and robust input validation.
- Standardized Responses: Adheres to the JSend specification with
success,fail, anderrorresponse types. - Customizable Status Labels: Allows custom status labels for flexible API designs.
- Input Validation: Ensures data is JSON-serializable and error messages are non-empty strings.
- Type Safety: Includes JSDoc annotations for TypeScript compatibility and better IDE support.
- Express Integration: Seamlessly integrates as middleware, attaching a
Jsendinstance to the Express response object. - Error Handling: Validates the Express response object and input parameters to prevent runtime errors.
Install the package via npm:
npm install jsend-middlewareEnsure you have Express.js installed in your project:
npm install expressAdd the jsendMiddleware to your Express application:
import express from "express";
import jsendMiddleware from "jsend-middleware";
const app = express();
// Apply JSend middleware
app.use(jsendMiddleware());
app.get("/example", (req, res) => {
res.jsend.success({ message: "Hello, World!" });
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});The middleware attaches a jsend object to the Express res object, providing three methods:
Used for successful requests.
res.jsend.success({ user: { id: 1, name: "John Doe" } });
// Response:
// {
// "status": "success",
// "data": { "user": { "id": 1, "name": "John Doe" } }
// }With custom status label and HTTP code:
res.jsend.success({ user: { id: 1, name: "John Doe" } }, 201, "ok");
// Response:
// {
// "status": "ok",
// "data": { "user": { "id": 1, "name": "John Doe" } }
// }Used for client-side errors (e.g., invalid input).
res.jsend.fail({ error: "Invalid email format" }, 400);
// Response:
// {
// "status": "fail",
// "data": { "error": "Invalid email format" }
// }Used for server-side or unexpected errors.
res.jsend.error("Database connection failed", 500, {
code: "DB_ERROR",
details: { retryAfter: 60 },
extra: { traceId: "abc123" },
});
// Response:
// {
// "status": "error",
// "message": "Database connection failed",
// "code": "DB_ERROR",
// "details": { "retryAfter": 60 },
// "extra": { "traceId": "abc123" }
// }The middleware supports configuration for default status labels:
app.use(
jsendMiddleware({
successLabel: "ok",
failLabel: "invalid",
errorLabel: "exception",
})
);
// Example success response with configured label
res.jsend.success({ message: "Configured!" });
// Response:
// {
// "status": "ok",
// "data": { "message": "Configured!" }
// }new Jsend(res);res: Express response object (required).- Throws an error if
resis not a valid Express response object.
-
success(data, status, statusLabel)data: Optional object or null (default:null).status: HTTP status code (default:200).statusLabel: Custom status label (default:"success").- Throws an error if
datais not JSON-serializable.
-
fail(data, status, statusLabel)data: Optional object or null (default:null).status: HTTP status code (default:400).statusLabel: Custom status label (default:"fail").- Throws an error if
datais not JSON-serializable.
-
error(message, status, options, statusLabel)message: Error message (default:"Internal Server Error").status: HTTP status code (default:500).options: Optional object withcode,details, andextrafields.statusLabel: Custom status label (default:"error").- Throws an error if
messageis not a non-empty string oroptions.extrais not an object.
jsendMiddleware(config);config: Optional configuration object.successLabel: Default label for success responses (default:"success").failLabel: Default label for fail responses (default:"fail").errorLabel: Default label for error responses (default:"error").
The middleware includes robust validation:
- Ensures the Express
resobject has required methods (status,json). - Validates that
datainsuccessandfailis an object ornull. - Ensures
messageinerroris a non-empty string. - Validates that
options.extrainerroris an object.
- Node.js >= 14.0.0
- Express.js >= 4.0.0
This project is licensed under the MIT License.
Contributions are welcome! Please submit a pull request or open an issue on the GitHub repository.
Inspired by the JSend specification for standardized JSON responses.