npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

next-respond

v1.0.1

Published

Simplify your NextJS API responses with clean, readable, and standardized HTTP status codes and messages.

Downloads

37

Readme

next-respond

Simplify your NextJS API responses with clean, readable, and standardized HTTP status codes and messages.

Why Use This Package?

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.

Instead of this:

try {
  return res.status(200).json({ result });
} catch (err) {
  return res.status(500).json({ message: "Internal Server Error" });
}

You can do this:

try {
  return Ok(res, null, { result });
} catch (err) {
  return InternalServerError(res);
}

Features

  • 🚀 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

Installation

npm install next-respond

or

yarn add next-respond

Usage

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);
    }
  }
}

API Reference

General Structure

All functions follow this pattern:

FunctionName(res, (message = null), (data = {}), (defaultMessage = true));
  • res: The NextJS response object
  • message: (Optional) A custom message to override the default
  • data: (Optional) Additional data to include in the response
  • defaultMessage: (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

Available Functions

  • 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

Examples

Here are some common usage examples and their corresponding outputs:

  1. BadRequest Response
BadRequest(res);

Output:

{
  "statusCode": 400,
  "message": "Bad Request"
}
  1. NotFound Response
NotFound(res);

Output:

{
  "statusCode": 404,
  "message": "Not Found"
}
  1. InternalServerError Response
InternalServerError(res);

Output:

{
  "statusCode": 500,
  "message": "Internal Server Error"
}
  1. Custom Message
InternalServerError(res, "Custom Error Message");

Output:

{
  "statusCode": 500,
  "message": "Custom Error Message"
}

Using HttpStatus and HttpStatusMessages

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] });
  }
}

Contributing

We welcome contributions!

License

This project is licensed under the MIT License.