You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 4-6.RSVP
Socket
Book a DemoInstallSign in
Socket

next-api-composer

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

next-api-composer

A helper utility for composing Next.js API routes with per-method implementations

1.1.1
latest
Source
npmnpm
Version published
Weekly downloads
506
-9.48%
Maintainers
1
Weekly downloads
 
Created
Source

Next API Composer

Your implementations of API Routes for your Next.js applications will be much easier with this library.

You have to code the API Routes like:

// api/example.ts
export default async (req, res) => {
  if (req.method === 'GET') {
    // do something
    res.json({ foo: 'bar' });
    return;
  }

  res.setHeader('Allow', 'GET');
  if (req.method === 'OPTIONS') {
    res.status(204).send(null);
  } else {
    res.status(405).send(null);
  }
};

With this library:

// api/example.ts
export default nextApi({
  GET: async (req, res) => {
    // do something
    res.json({ foo: 'bar' });
  },
});

Installation

  • npm i next-api-composer

Supported Methods

  • GET
  • POST
  • PUT
  • PATCH
  • DELETE

HTTP Error Handling

  • This library includes various HTTP Error types such as HTTP400BadRequest, which extends RouteError.
  • RouteError has a method send(res: Sendable).
  • If any errors extending RouteError is thrown in the handler, they'll be handled with calling the send method of the error.
  • If any errors other than RouteError is thrown in the handler, the handler will emit HTTP 500 error.
  • For details, see src/index.ts.
// api/example.ts
export default nextApi({
  GET: async (req, res) => {
    // Given, the function authenticate will return false
    // if the request does not have a valid token in its HTTP header.
    if (!authenticate(req)) {
      throw new HTTP401Unauthorized();
    }

    // do something
    res.json({ foo: 'bar' });
  },
});

Keywords

next

FAQs

Package last updated on 03 Apr 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts