Simplify your NextJS API responses with clean, readable, and standardized HTTP status codes and messages.
When building NextJS APIs, handling HTTP responses can become repetitive and error-prone. This package provides a set of easy-to-use functions for sending HTTP status codes and responses, making your code cleaner, more readable, and less prone to errors.
try {
return res.status(200).json({ result });
} catch (err) {
return res.status(500).json({ message: "Internal Server Error" });
}try {
return Ok(res, null, { result });
} catch (err) {
return InternalServerError(res);
}- 🚀 Easy-to-use functions for all standard HTTP status codes
- 📚 Consistent error messages based on HTTP standards
- 🛠 Customizable messages and data payloads
- 🧩 Seamless integration with NextJS API routes
- 🔒 Type-safe with full TypeScript support
npm install next-respondor
yarn add next-respondImport the functions you need in your NextJS API route:
import { Ok, BadRequest, InternalServerError } from "next-respond";
export default function handler(req, res) {
try {
// Your API logic here
return Ok(res, null, { data: result });
} catch (error) {
if (error instanceof ValidationError) {
return BadRequest(res);
} else {
return InternalServerError(res);
}
}
}All functions follow this pattern:
FunctionName(res, (message = null), (data = {}), (defaultMessage = true));res: The NextJS response objectmessage: (Optional) A custom message to override the defaultdata: (Optional) Additional data to include in the responsedefaultMessage: (Optional) A boolean that indicates whether to include the default status text in the response. Defaults to true, meaning the status text will always be included
- Information responses:
Continue,SwitchingProtocols,Processing,EarlyHints - Successful responses:
Ok,Created,Accepted,NonAuthoritativeInformation,NoContent,ResetContent,PartialContent - Redirection messages:
Ambiguous,MovedPermanently,Found,SeeOther,NotModified,TemporaryRedirect,PermanentRedirect - Client error responses:
BadRequest,Unauthorized,PaymentRequired,Forbidden,NotFound,MethodNotAllowed,NotAcceptable,ProxyAuthenticationRequired,RequestTimeout,Conflict,Gone,LengthRequired,PreconditionFailed,PayloadTooLarge,UriTooLong,UnsupportedMediaType,RequestedRangeNotSatisfiable,ExpectationFailed,IAmATeapot,Misdirected,UnprocessableEntity,FailedDependency,PreconditionRequired,TooManyRequests - Server error responses:
InternalServerError,NotImplemented,BadGateway,ServiceUnavailable,GatewayTimeout,HttpVersionNotSupported
Here are some common usage examples and their corresponding outputs:
- BadRequest Response
BadRequest(res);Output:
{
"statusCode": 400,
"message": "Bad Request"
}- NotFound Response
NotFound(res);Output:
{
"statusCode": 404,
"message": "Not Found"
}- InternalServerError Response
InternalServerError(res);Output:
{
"statusCode": 500,
"message": "Internal Server Error"
}- Custom Message
InternalServerError(res, "Custom Error Message");Output:
{
"statusCode": 500,
"message": "Custom Error Message"
}You can also import HttpStatus and HttpStatusMessages to use them directly when building custom responses or performing other status-related tasks.
import { HttpStatus, HttpStatusMessages } from "next-respond";
export default function handler(req, res) {
if (someCondition) {
res
.status(HttpStatus.OK)
.json({ message: HttpStatusMessages[HttpStatus.OK] });
} else {
res
.status(HttpStatus.BAD_REQUEST)
.json({ message: HttpStatusMessages[HttpStatus.BAD_REQUEST] });
}
}We welcome contributions!
This project is licensed under the MIT License.