Skip to main content

Getting Started

Introduction

Create Endpoint Factory (CEF) is a utility written to make the process of creating a NextJS API route handler quicker and more type-safe.

It allows you to define a handler per HTTP method (GET, POST, etc.) and consolidates them into a final handler which will call the according method, or return a 405 response if the method is unsupported (unless a default handler is provided).

It also provides some handy abstractions around returning data/catching errors.

Features

  • One time authentication setup (with the ability to disable for a given route)
  • Automatic handling of unsupported methods and OPTIONS requests
  • Automatic status code based on handler return
  • Customisable serialisation of uncaught errors
  • Customisable derivation of extra data from request
  • Parsing of body and query params

Installation

CEF is available as a package on NPM:

npm install next-create-endpoint-factory

Setup

The main export from CEF is the createEndpointFactory function, which is used to make the prepared createEndpoint factory used for each NextJS API route.

note

You're able to name this returned factory anything you like - in this documentation we'll be using createEndpoint.

The framework also doesn't mind where you export this factory from, as long as you're happy importing it into your API routes.

import { createEndpointFactory } from 'next-create-endpoint-factory';

export const createEndpoint = createEndpointFactory();

This function can optionally accept some configuration, covered in concepts.

Once this createEndpoint function is created, you can import it into your API route.

Endpoints

At its base level, an endpoint defines handlers for incoming method requests.

These handlers may return data that should be sent as a response, and the final status will be set based on this.

Handler resultStatusFinal response
Data returned200Data sent via res.json()
No data returned (undefined)204res.end() called
Error thrown500Serialised error sent via res.json()
tip

See custom codes for how to use codes other than these defaults.

The final combined handler will be attached to the endpoint instance. In the vast majority of cases, you'll want to export this as default.

The combined handler receives the original request and response objects, and automatically calls the corresponding handler with data about the request and an API for responses - if no handler is found for the method, a 405 is sent along with an Allow header set to a list of supported methods.

This handler also automatically supports OPTIONS requests.

pages/api/foo.ts
import { createEndpoint } from '../../src/api';

const endpoint = createEndpoint({
methods: (method) => ({
get: method<string>({
handler: () => {
return 'foo';
},
}),
post: method<void>({
handler: ({ body }, { failWithCode }) => {
console.log(body);
if (!body) {
throw failWithCode(400, 'no body');
}
},
}),
}),
});

export default endpoint.handler;