Simplify your NextJS API responses with clean, readable, and standardized HTTP status codes and messages.
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);
}
npm install next-respond
or
yarn add next-respond
Import 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 includedContinue
, SwitchingProtocols
, Processing
, EarlyHints
Ok
, Created
, Accepted
, NonAuthoritativeInformation
, NoContent
, ResetContent
, PartialContent
Ambiguous
, MovedPermanently
, Found
, SeeOther
, NotModified
, TemporaryRedirect
, PermanentRedirect
BadRequest
, Unauthorized
, PaymentRequired
, Forbidden
, NotFound
, MethodNotAllowed
, NotAcceptable
, ProxyAuthenticationRequired
, RequestTimeout
, Conflict
, Gone
, LengthRequired
, PreconditionFailed
, PayloadTooLarge
, UriTooLong
, UnsupportedMediaType
, RequestedRangeNotSatisfiable
, ExpectationFailed
, IAmATeapot
, Misdirected
, UnprocessableEntity
, FailedDependency
, PreconditionRequired
, TooManyRequests
InternalServerError
, NotImplemented
, BadGateway
, ServiceUnavailable
, GatewayTimeout
, HttpVersionNotSupported
Here are some common usage examples and their corresponding outputs:
BadRequest(res);
Output:
{
"statusCode": 400,
"message": "Bad Request"
}
NotFound(res);
Output:
{
"statusCode": 404,
"message": "Not Found"
}
InternalServerError(res);
Output:
{
"statusCode": 500,
"message": "Internal Server Error"
}
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.