🚀 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

1.2.0
Source
npm
Version published
Weekly downloads
2.2K
-3.91%
Maintainers
1
Weekly downloads
 
Created
Source


Next REST Framework

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


CI status Github Stars Bundle Size License 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
  • An example application for live demo and local development

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 Zod. The schemas are automatically converted to JSON schema format for the auto-generated OpenAPI specifications.
  • Supports auto-generated openapi.json and openapi.yaml documents for which you can include your existing OpenAPI specification.
  • 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 - 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:

App Router:

// src/next-rest-framework/client.ts

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

export const { defineCatchAllRoute, defineRoute } = NextRestFramework({
  appDirPath: 'src/app', // Path to your app directory.
  deniedPaths: ['/api/auth/**'] // Paths that are not using Next REST Framework if you have any.
});

Pages Router:

// src/next-rest-framework/client.ts

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

export const { defineCatchAllApiRoute, defineApiRoute } = NextRestFramework({
  apiRoutesPath: 'src/pages/api', // Path to your API routes directory.
  deniedPaths: ['/api/auth/**'] // Paths that are not using Next REST Framework if you have any.
});

You can also use both App Router and Pages Router simultaneously by combining the examples above.

The complete API of the initialized client is the following:

NameDescription
defineCatchAllRoute A function for defining a single catch-all route when using App Router. Must be used in the root of your app directory in the following path [[...next-rest-framework]]/route.ts.
defineCatchAllApiRoute A function for defining a single catch-all API route when using Pages Router. Must be used in the root of your API routes folder in the following path pages/api/[[...next-rest-framework]].ts.
defineRouteA function for defining an individual route that you want to use Next REST Framework for when using App Router. Can also be used in other catch-all API routes.
defineApiRouteA function for defining an individual API route that you want to use Next REST Framework for when using Pages Router. Can also be used in other catch-all API routes.

Initialize catch-all route

To initialize Next REST Framework you need to export and call the defineCatchAllRoute function when using App Router, or defineCatchAllApiRoute function when using Pages Router from a root-level optional catch-all API route:

// src/app/[[...next-rest-framework]]/route.ts

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

export const GET = defineCatchAllRoute();

OR:

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

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

export default defineCatchAllApiRoute();

This is enough to get you started. Your application should use the catch-all function only once. If you want to define additional catch-all routes, you can use the defineRoute or defineApiRoute functions for those. 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.
  • A local openapi.json file that will be generated as you run npx next-rest-framework generate or call any of the above endpoints in development mode. This file should be under version control and you should always keep it in the project root. It will be automatically updated as you develop your application locally and is used by Next REST Framework when you run your application in production. Remember that it will be dynamically regenerated every time you call any of the above endpoints in development mode. A good practice is also to generate this file as part of your pre-commit hooks or before deploying your changes to production with next-rest-framework generate.

The reserved OpenAPI paths are configurable with the Config options that you can pass for your NextRestFramework client.

Add an API Route

App Router:

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

import { defineRoute } from 'next-rest-framework/client';
import { NextResponse } from 'next/server';
import { z } from 'zod';

const handler = defineRoute({
  GET: {
    output: [
      {
        status: 200,
        contentType: 'text/html',
        schema: z.object({
          foo: z.string(),
          bar: z.string(),
          baz: z.string(),
          qux: z.string()
        })
      }
    ],
    handler: () => {
      // Any other JSON format will lead to TS error.
      return NextResponse.json(
        { foo: 'foo', bar: 'bar', baz: 'baz', qux: 'qux' },
        {
          status: 200,
          headers: { 'Content-Type': 'text/plain' }
        }
      );
    }
  },
  POST: {
    input: {
      contentType: 'application/json',
      body: z.object({
        foo: z.string(),
        bar: z.number()
      }),
      query: z.object({
        test: z.string()
      })
    },
    output: [
      {
        status: 201,
        contentType: 'application/json',
        schema: z.object({
          foo: z.string(),
          bar: z.number(),
          query: z.object({
            test: z.string()
          })
        })
      }
    ],
    // A strongly-typed Route Handler: https://nextjs.org/docs/app/building-your-application/routing/route-handlers
    handler: async (
      req,
      {
        params: {
          test // Strongly typed.
        }
      }
    ) => {
      const { foo, bar } = await req.json();

      // Any other JSON format will lead to TS error.
      return NextResponse.json(
        { foo, bar, query: { test } },
        {
          status: 201
        }
      );
    }
  }
});

export { handler as GET, handler as POST };

Pages Router:

// src/pages/api/todos.ts

import { defineApiRoute } from 'next-rest-framework/client';
import { z } from 'zod';

export default defineApiRoute({
  GET: {
    output: [
      {
        status: 200,
        contentType: 'application/json',
        schema: z.object({
          foo: z.string(),
          bar: z.string(),
          baz: z.string(),
          qux: z.string()
        })
      }
    ],
    handler: (_req, res) => {
      res.status(200).json({ foo: 'foo', bar: 'bar', baz: 'baz', qux: 'qux' });
    }
  },
  POST: {
    input: {
      contentType: 'application/json',
      body: z.object({
        foo: z.string(),
        bar: z.number()
      }),
      query: z.object({
        test: z.string()
      })
    },
    output: [
      {
        status: 201,
        contentType: 'application/json',
        schema: z.object({
          foo: z.string(),
          bar: z.number(),
          query: z.object({
            test: z.string()
          })
        })
      }
    ],
    handler: ({ body: { foo, bar }, query: { test } }, res) => {
      res.status(201).json({ foo, bar, query: { test } });
    }
  }

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

Next REST Framework Swagger UI

API reference

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
appDirPath Absolute path from the project root to the root directory where your Routes are located when using App Router. Next REST Framework uses this as the root directory to recursively search for your Routes, so being as specific as possible will improve performance. This option is not required when using Pages Router, but it can be used together with the apiRoutesPath option when using both routers at the same time.
apiRoutesPath Absolute path from the project root to the root directory where your API Routes are located when using Pages Router. Next REST Framework uses this as the root directory to recursively search for your API Routes, so being as specific as possible will improve performance. This option is not required when using App Router, but it can be used together with the appDirPath option when using both routers at the same time.
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.
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.
swaggerUiConfigA SwaggerUI config object for customizing the generated SwaggerUI.
exposeOpenApiSpecSetting this to false will serve none of the OpenAPI documents neither the Swagger UI. Defaults to true.
errorHandlerAn error handler function used to catch errors in your routes. Both synchronous and asynchronous handlers are supported. The function takes in the same parameters as the Next.js App Router and API Routes handlers. 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.
generatePathsTimeoutTimeout in milliseconds for generating the OpenAPI spec. Defaults to 5000. For large applications you might have to increase this.

Route config

The route config parameters define an individual route, applicable for all endpoints (methods) that are using that route:

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

Method handlers

The method handler parameters define an individual endpoint:

NameDescriptionRequired
inputAn Input object object.false
outputAn array of Output objects. true
handler Your handler function that takes in your typed request and response (when using Pages Router). Both synchronous and asynchronous handlers are supported. The function takes in strongly-typed versions of the same parameters as the Next.js App Router and API Routes handlers.true
openApiSpecOverridesAn OpenAPI Operation object that can be used to override and extend the auto-generated and higher level specifications.false
Input object

The input object is used for the validation and OpenAPI documentation of the incoming request:

NameDescriptionRequired
contentTypeThe content type header of the request. A request with no content type header or a incorrect content type header will get an error response.true
bodyA Zod schema describing the format of the request body.true
queryA Zod schema describing the format of the query parameters.false
Output object

The output objects define what kind of responses are returned from your API handler and is used for the OpenAPI documentation of the response:

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. A response body not matching to the schema will lead to a TS error. true

SwaggerUI config

The SwaggerUI config object can be used to customize the generated Swagger UI:

NameDescription
defaultThemeDefault theme (light/dark) to use for SwaggerUI - defaults to "light"
titleCustom page title meta tag value.
descriptionCustom page description meta tag value.
logoHrefAn href for a custom logo.
faviconHrefAn href for a custom favicon.

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 27 Sep 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