🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more
Socket
Book a DemoInstallSign in
Socket

next-rest-framework

Package Overview
Dependencies
Maintainers
1
Versions
86
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

next-rest-framework

Next REST Framework - write type-safe, self-documenting REST APIs in Next.js

0.1.0
Source
npm
Version published
Weekly downloads
1.6K
-38.42%
Maintainers
1
Weekly downloads
 
Created
Source


Next REST Framework

Type-safe, self-documenting REST APIs for Next.js


CI status Contributor Covenant 2.1

Table of contents

Overview

Next REST Framework is an open-source, opinionated, lightweight, easy-to-use set of tools to build type-safe, self-documenting HTTP REST APIs with Next.js. Building OpenAPI specification-compliant REST APIs can be cumbersome and slow but Next REST Framework makes this easy with auto-generated OpenAPI documents and Swagger UI using TypeScript and object schemas.

This is a monorepo containing the following packages / projects:

  • The primary next-rest-framework package
  • A development test application

Features

Lightweight, type-safe, easy to use

  • Designed to work with TypeScript so that your request bodies, responses, headers etc. are strongly typed.
  • Object-schema validation with popular libraries like Zod or Yup
  • Supports auto-generated openapi.json and openapi.yaml documents for which you can include your existing OpenAPI specification.
  • Supports any kind of middleware logic that you want to use for authentication etc. See more in Middlewares. Also works with other Next.js server-side libraries, like NextAuth.js.
  • Fully customizable - You can decide which routes Next REST Framework will use to serve your API docs etc. and it can be easily customized to work with any kind of existing Next.js REST API.

Installation

npm install --save next-rest-framework

Getting started

Initialize client

To use Next REST Framework you need to initialize the client somewhere in your Next.js project. The client exposes all functionality of the framework you will need:

// next-rest-framework/client.ts

import { NextRestFramework } from 'next-rest-framework';

export const { defineCatchAllHandler, defineEndpoints } = NextRestFramework();

The complete API of the initialized client is the following:

NameDescription
defineCatchAllHandler A function used to generate your single catch-all API route. Must be used in the root of your API routes folder in the following path pages/api/[[...next-rest-framework]].ts.
defineEndpointsUsed for all other API routes that you want to use Next REST Framework for. Can also be used in other catch-all API routes.
getOpenApiSpecA function that exposes the generated OpenAPI spec combined with your own definitions. Useful if you want to e.g. export the OpenAPI spec to a separate file.

Initialize catch-all handler

To initialize Next REST Framework you need to export and call the defineCatchAllHandler function from a root-level optional catch-all API route:

// pages/api/[[...next-rest-framework]].ts

import { defineCatchAllHandler } from 'next-rest-framework/client';

export default defineCatchAllHandler();

This is enough to get you started. By default Next REST Framework gives you three API routes with this configuration:

  • /api: Swagger UI using the auto-generated OpenAPI spec.
  • /api/openapi.json: An auto-generated openapi.json document.
  • /api/openapi.yaml: An auto-generated openapi.yaml document.

All of these are configurable with the Config options that you can pass for your NextRestFramework client. You can also use your existing catch-all logic simply by passing a Route config to your defineCatchAllHandler if you want to use e.g. custom 404 handlers, redirections etc.

Add an API Route

// pages/api/todos.ts

import { object, string, number, boolean, array } from 'zod';
import { defineEndpoints } from 'next-rest-framework/client';

// Can be a `zod` schema as well.
const todoSchema = object({
  id: string(),
  name: string(),
  completed: boolean()
});

export default defineEndpoints({
  GET: {
    responses: [
      {
        status: 200,
        contentType: 'application/json',
        schema: object({
          data: array(todoSchema)
        })
      }
    ],
    handler: ({ res }) => {
      // Using any other content type, status code or response data format will lead to TS error.
      res.setHeader('content-type', 'application/json');
      res.status(200).json({
        data: [
          {
            id: 'foo',
            name: 'bar',
            completed: true
          }
        ]
      });
    }
  },
  POST: {
    requestBody: {
      contentType: 'application/json',
      schema: object({
        name: string()
      })
    },
    responses: [
      {
        status: 201,
        contentType: 'application/json',
        schema: object({
          data: todoSchema
        })
      }
    ],
    handler: ({
      res,
      req: {
        body: {
          name // Any other attribute will lead to TS error.
        }
      }
    }) => {
      const todo = createYourTodo(name);
      res.setHeader('content-type', 'application/json');
      res.status(201).json({
        data: todo
      });
    }
  }
});

These type-safe endpoints will be now auto-generated to your OpenAPI spec and Swagger UI!

Config options

The optional config options allow you to customize Next REST Framework. The following options can be passed as a parameter for your NextRestFramework client in an object:

NameDescription
openApiSpecYour custom OpenAPI Object that will be merged with the auto-generated spec. Defaults to a minimum config required for the OpenAPI spec generation.
openApiJsonPathCustom path for serving openapi.json file. Defaults to /api/openapi.json.
openApiYamlPathCustom path for serving openapi.yaml file. Defaults to /api/openapi.yaml.
swaggerUiPathCustom path for service Swagger UI. Defaults to /api.
exposeOpenApiSpecSetting this to false will serve none of the OpenAPI documents neither the Swagger UI. Defaults to true.
middlewareA global middleware for all of your API routes. See Global middleware for more information.
errorHandlerA Global error handler for all of your API routes. Defaults to a basic error handler logging the errors in non-production mode.
suppressInfoSetting this to true will suppress all informational logs from Next REST Framework. Defaults to false.

Route config

In addition to your method handlers, middleware and errorHandler, you can also configure OpenAPI Path Item Object parameters for your API route and they will automatically become part of your auto-generated OpenAPI spec The following options can be passed as a parameter for your defineCatchAllHandler and defineEndpoints in an object:

NameDescriptionRequired
GET | PUT | POST | DELETE | OPTIONS | HEAD | PATCH | TRACEA Method handler object.true
middleware A Middleware function that takes in the return values from your Global middleware.false
errorHandlerA Route error handler for this API route, overriding the Global error handler.false
$refA reference to another Path Item Object.false
descriptionA string description, intended to apply to all operations in this path. CommonMark syntax MAY be used for rich text representation.false
serversAn array of Server Objects.false
parametersAn array of Parameter objects or Reference objects.false

Method handlers

NameDescriptionRequired
requestBodyA Request body object.false
responsesAn array of Response objects. true
middlewareA Middleware function that takes in the return values from both your Global middleware and Route middleware. false
handler Your Handler function that takes in your typed request, response and Middleware parameters and contains all of your business logic.true
errorHandlerA Method error handler for this method, overriding both the Global error handler and Route error handler.false

Request body

The required properties are used for internal type-checking and the optional properties are used for OpenAPI spec generation and come from the OpenAPI Request Body Object and Media Type Object specification.

NameDescriptionRequired
contentTypeThe content type that all requests must have - requests with no content type or incorrect content type will get an error response.true
schemaA Zod or Yup schema describing the format of the request body.true
description A brief description of the request body. This could contain examples of use. CommonMark syntax MAY be used for rich text representation. false
requiredDetermines if the request body is required in the request. All requests without a body will get an error response when this is set to true. Defaults to false.false
exampleAn example object matching the schema.false
examplesA mapping of Example Objects or Reference Objects matching the schema. false
encodingA mapping of Encoding Objects. false

Response object

NameDescriptionRequired
descriptionA short description of the response. CommonMark syntax MAY be used for rich text representation. true
statusA possible status code returned by your API route.true
contentTypeThe content type of the response. Using any other content-type will lead to a TS error.true
schemaA Zod or Yup schema describing the format of the response data. All response data not matching to the schema will lead to a TS error. true
headersA mapping of headers to Header Objects or Reference Objects.false
links A mapping of Link Objects or Reference Objects.false

Handler

The handler function takes care of your actual business logic, supporting both synchronous and asynchronous execution and taking in an object with three strongly typed parameters:

NameDescription
req A strongly-typed NextApiRequest object containing the typed body of your request.
resA strongly-typed NextApiResponse object that allows you to use only pre-defined status codes, Content-Type headers and response data formats from the current method handler.
paramsAn object containing the strongly-typed combined response of your Global middleware, Route middleware and Method middleware. The parameters can also be overridden in the different middleware layers with the Method middleware taking precedence over the Route middleware and route middleware taking precedence over Global middleware

Middlewares

The middleware functions can be used for any kind of middleware logic, like adding authentication etc. for your API. In addition, they can be used to add additional typed parameters for your API route handlers. They support both asynchronous and synchronous execution.

// A global middleware, route middleware or method middleware.
middleware: () => ({
  foo: 'bar'
});
// A method handler (given that the middleware above is either in the same API route or method, or is a global middleware).
handler: ({
  params: {
    foo // string
  }
}) => {
  // Your logic.
};

Global middleware

The global middleware function takes in an object with two attributes and optionally returns an object of any form:

NameDescription
req A plain NextApiRequest object.
resA plain NextApiResponse object.

Route middleware

The route middleware function takes in an object with three attributes and optionally returns an object of any form:

NameDescription
req A plain NextApiRequest object.
resA plain NextApiResponse object.
params The type of an object returned by your Global middleware.

Method middleware

The method middleware function takes in an object with three attributes and optionally returns an object of any form:

NameDescription
req A strongly-typed NextApiRequest object containing the typed body of your request.
resA strongly-typed NextApiResponse object that allows you to use only pre-defined status codes, Content-Type headers and response data formats from the current method handler.
params The type of a combined object returned by both your Global middleware and Route middleware.

Error handlers

The error handler functions can be used for custom error handling. They support both asynchronous and synchronous execution.

// A global error handler, route error handler or method error handler.
errorHandler: ({ req, res, params }) => {
  // Your error handling logic.
};

Global error handler

The global error handler takes in an object with two attributes:

NameDescription
req A plain NextApiRequest object.
resA plain NextApiResponse object.

Route error handler

Route error handler can be used to override your global error handler. The route error handler takes in an object with three attributes:

NameDescription
req A plain NextApiRequest object.
resA plain NextApiResponse object.
params The type of a combined object returned by both your Global middleware and Route middleware.

Method error handler

Method error handler can be used to override both your global error handler and route error handler. The method error handler takes in an object with three attributes and optionally returns an object of any form:

NameDescription
req A strongly-typed NextApiRequest object containing the typed body of your request.
resA strongly-typed NextApiResponse object that allows you to use only pre-defined status codes, Content-Type headers and response data formats from the current method handler.
params The type of a combined object returned by your Global middleware, Route middleware and Method middleware.

Changelog

See the changelog in CHANGELOG.md

Contributing

All contributions are welcome!

License

ISC, see full license in LICENSE.

Keywords

nextjs

FAQs

Package last updated on 06 Dec 2022

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