3.4.2 • Published 6 months ago

@ctdio/next-rest-framework v3.4.2

Weekly downloads
-
License
ISC
Repository
github
Last release
6 months ago

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 docs using TypeScript and object schemas.

This is a monorepo containing the following packages / projects:

  1. The primary next-rest-framework package
  2. An example application for live demo and local development

Features

Lightweight, type-safe, easy to use

  • Designed to work with TypeScript so that your requests and responses are strongly typed.
  • Object-schema validation with Zod. The object schemas are automatically converted to JSON schema format for the auto-generated OpenAPI specification.
  • Auto-generated and extensible openapi.json spec file from your business logic.
  • Auto-generated Redoc and/or SwaggerUI documentation frontend.
  • Works with Next.js Middleware and other server-side libraries, like NextAuth.js.
  • Supports both Next.js App Router and Pages Router, even at the same time.
  • Fully customizable and compatible with any existing Next.js project.

Installation

npm install --save next-rest-framework

Getting started

Create docs handler

To get access to the auto-generated documentation, initialize the docs endpoint somewhere in your codebase. You can also skip this step if you don't want to expose a public API documentation.

App Router:

// src/app/api/route.ts

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

export const GET = docsRouteHandler();

Pages Router:

// src/pages/api.ts

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

export default docsApiRouteHandler();

This is enough to get you started. Now you can access the API documentation in your browser. Calling this endpoint will automatically generate the openapi.json OpenAPI specification file, located in the public folder by default. You can also configure this endpoint to disable the automatic generation of the OpenAPI spec file or use the CLI command npx next-rest-framework generate to generate it. You can also create multiple docs endpoints for various use cases. See the full configuration options of this endpoint in the Docs handler options section.

Create endpoint

App Router:

// src/app/api/todos/route.ts

import {
  TypedNextResponse,
  routeHandler,
  routeOperation
} from 'next-rest-framework';
import { z } from 'zod';

const TODOS = [
  {
    id: 1,
    name: 'TODO 1',
    completed: false
  }
];

// Example App Router route handler with GET/POST handlers.
const handler = routeHandler({
  GET: routeOperation({
    // Optional OpenAPI operation documentation.
    operationId: 'getTodos',
    tags: ['example-api', 'todos', 'app-router']
  })
    // Output schema for strictly-typed responses and OpenAPI documentation.
    .output([
      {
        status: 200,
        contentType: 'application/json',
        schema: z.array(
          z.object({
            id: z.number(),
            name: z.string(),
            completed: z.boolean()
          })
        )
      }
    ])
    .handler(() => {
      // Type-checked response.
      return TypedNextResponse.json(TODOS, {
        status: 200
      });
    }),

  POST: routeOperation({
    // Optional OpenAPI operation documentation.
    operationId: 'createTodo',
    tags: ['example-api', 'todos', 'app-router']
  })
    // Input schema for strictly-typed request, request validation and OpenAPI documentation.
    .input({
      contentType: 'application/json',
      body: z.object({
        name: z.string()
      })
    })
    // Output schema for strictly-typed responses and OpenAPI documentation.
    .output([
      {
        status: 201,
        contentType: 'application/json',
        schema: z.string()
      },
      {
        status: 401,
        contentType: 'application/json',
        schema: z.string()
      }
    ])
    // Optional middleware logic executed before request validation.
    .middleware((req) => {
      if (!req.headers.get('authorization')) {
        // Type-checked response.
        return TypedNextResponse.json('Unauthorized', {
          status: 401
        });
      }
    })
    .handler(async (req) => {
      const { name } = await req.json(); // Strictly-typed request.

      // Type-checked response.
      return TypedNextResponse.json(`New TODO created: ${name}`, {
        status: 201
      });
    })
});

export { handler as GET, handler as POST };

The TypedNextResponse ensures that the response status codes and content-type headers are type-checked. You can still use the regular NextResponse if you prefer to have less type-safety.

Pages Router:

// src/pages/api/todos.ts

import { apiRouteHandler, apiRouteOperation } from 'next-rest-framework';
import { z } from 'zod';

const TODOS = [
  {
    id: 1,
    name: 'TODO 1',
    completed: false
  }
];

// Example Pages Router API route with GET/POST handlers.
export default apiRouteHandler({
  GET: apiRouteOperation({
    // Optional OpenAPI operation documentation.
    operationId: 'getTodos',
    tags: ['example-api', 'todos', 'pages-router']
  })
    // Output schema for strictly-typed responses and OpenAPI documentation.
    .output([
      {
        status: 200,
        contentType: 'application/json',
        schema: z.array(
          z.object({
            id: z.number(),
            name: z.string(),
            completed: z.boolean()
          })
        )
      }
    ])
    .handler((_req, res) => {
      // Type-checked response.
      res.status(200).json(TODOS);
    }),

  POST: apiRouteOperation({
    // Optional OpenAPI operation documentation.
    operationId: 'createTodo',
    tags: ['example-api', 'todos', 'pages-router']
  })
    // Input schema for strictly-typed request, request validation and OpenAPI documentation.
    .input({
      contentType: 'application/json',
      body: z.object({
        name: z.string()
      })
    })
    // Output schema for strictly-typed responses and OpenAPI documentation.
    .output([
      {
        status: 201,
        contentType: 'application/json',
        schema: z.string()
      },
      {
        status: 401,
        contentType: 'application/json',
        schema: z.string()
      }
    ])
    // Optional middleware logic executed before request validation.
    .middleware((req, res) => {
      if (!req.headers.authorization) {
        res.status(401).json('Unauthorized'); // Type-checked response.
      }
    })
    .handler((req, res) => {
      const { name } = req.body; // Strictly-typed request.
      res.status(201).json(`New TODO created: ${name}`); // Type-checked response.
    })
});

These type-safe endpoints will be now auto-generated to your OpenAPI spec:

Next REST Framework docs

API reference

Docs handler options

The following options can be passed to the docsRouteHandler (App Router) and docsApiRouteHandler (Pages Router) functions for customizing Next REST Framework:

NameDescription
deniedPathsArray of paths that are denied by Next REST Framework and not included in the OpenAPI spec. Supports wildcards using asterisk * and double asterisk ** for recursive matching. Example: ['/api/disallowed-path', '/api/disallowed-path-2/*', '/api/disallowed-path-3/**'] Defaults to no paths being disallowed.
allowedPathsArray of paths that are allowed by Next REST Framework and included in the OpenAPI spec. Supports wildcards using asterisk * and double asterisk ** for recursive matching. Example: ['/api/allowed-path', '/api/allowed-path-2/*', '/api/allowed-path-3/**'] Defaults to all paths being allowed.
openApiObjectAn OpenAPI Object that can be used to override and extend the auto-generated specification.
openApiJsonPathPath that will be used for fetching the OpenAPI spec - defaults to /openapi.json. This path also determines the path where this file will be generated inside the public folder.
autoGenerateOpenApiSpecSetting this to false will not automatically update the generated OpenAPI spec when calling the docs handler endpoints. Defaults to true.
docsConfigA Docs config object for customizing the generated docs.
suppressInfoSetting this to true will suppress all informational logs from Next REST Framework. Defaults to false.

Docs config

The docs config options can be used to customize the generated docs:

NameDescription
providerDetermines whether to render the docs using Redoc (redoc) or SwaggerUI swagger-ui. Defaults to redoc.
titleCustom title, used for the visible title and HTML title.
descriptionCustom description, used for the visible description and HTML meta description.
faviconUrlCustom HTML meta favicon URL.
logoUrlA URL for a custom logo.

Route handler options

The following options cam be passed to the routeHandler (App Router) and apiRouteHandler (Pages Router) functions to create new API endpoints:

NameDescriptionRequired
GET \| PUT \| POST \| DELETE \| OPTIONS \| HEAD \| PATCHA Method handler object.true
openApiPathAn OpenAPI Path Item Object that can be used to override and extend the auto-generated specification.false

Route operations

The route operation functions routeOperation (App Router) and apiRouteOperation (Pages Router) allow you to define your API handlers for your endpoints. These functions accept an OpenAPI Operation object as a parameter, that can be used to override the auto-generated specification. Calling this function allows you to chain your API handler logic with the following functions.

NameDescription
inputAn Input function for defining the validation and documentation of the request.
outputAn Output function for defining the validation and documentation of the response.
handlerA Handler function for defining your business logic.
middlewareA Middleware function that gets executed before the request input is validated.

Input

The input function is used for type-checking, validation and documentation of the request, taking in an object with the following properties:

NameDescriptionRequired
contentTypeThe content type header of the request. When the content type is defined, a request with an incorrect content type header will get an error response.false
bodyA Zod schema describing the format of the request body. When the body schema is defined, a quest with an invalid request body will get an error response.false
queryA Zod schema describing the format of the query parameters. When the query schema is defined, a request with invalid query parameters will get an error response.false

Calling the input function allows you to chain your API handler logic with the Output, Middleware and Handler functions.

Output

The output function is used for type-checking and documentation of the response, taking in an array of objects with the following properties:

NameDescriptionRequired
statusA status code that your API can return.true
contentTypeThe content type header of the response.true
schemaA Zod schema describing the format of the response data. true

Calling the input function allows you to chain your API handler logic with the Middleware and Handler functions.

Middleware

The middleware function is executed before validating the request input. The function takes in the same parameters as the Next.js Route Handlers and API Routes handlers.

Handler

The handler function is a strongly-typed function to implement the business logic for your API. The function takes in strongly-typed versions of the same parameters as the Next.js Route Handlers and API Routes handlers.

CLI

The Next REST Framework CLI supports generating and validating the openapi.json file:

  • npx next-rest-framework generate to generate the openapi.json file.
  • npx next-rest-framework validate to validate that the openapi.json file is up-to-date.

The next-rest-framework validate command is useful to have as part of the static checks in your CI/CD pipeline. Both commands support the following options:

NameDescription
--skipBuild <boolean>By default, next build is used to build your routes. If you have already created the build, you can skip this step by setting this to true.
--distDir <string>Path to your production build directory. Defaults to .next.
--timeout <string>The timeout for generating the OpenAPI spec. Defaults to 60 seconds.
--configPath <string>In case you have multiple docs handlers with different configurations, you can specify which configuration you want to use by providing the path to the API. Example: /api/my-configuration.

Changelog

See the changelog in CHANGELOG.md

Contributing

All contributions are welcome!

License

ISC, see full license in LICENSE.