Skip to content
These docs describe arocapi v5, which is in beta. Install it with pnpm add arocapi@beta.

HTTP

arocapi has no options of its own for HTTP behaviour. These are settings on your Fastify app.

Setting Where Default Purpose
CORS @fastify/cors on your app no CORS headers Let browsers on other origins call the API.
errorHandler setErrorHandler on your app arocapi’s routes only Answer your own routes’ errors in arocapi’s envelope.
notFoundHandler setNotFoundHandler on your app your app’s handler Answer unknown paths in arocapi’s envelope.
prefix Fastify’s register options none Mount arocapi under a path, with its own 404 for unknown paths.

arocapi doesn’t set CORS headers. To let browsers on other origins call it, register @fastify/cors on your root instance before arocapi:

Terminal window
pnpm add @fastify/cors

Its defaults allow every origin with GET, HEAD and POST, which covers all of arocapi’s routes.

arocapi’s routes answer errors as { error: { code, message, details? } }; the codes and statuses are listed under Error responses. To give your own routes and unknown paths the same envelope, set arocapi’s handlers on the root instance:

import { errorHandler, notFoundHandler } from 'arocapi';
import Fastify from 'fastify';
const fastify = Fastify();
fastify.setErrorHandler(errorHandler);
fastify.setNotFoundHandler(notFoundHandler);

To report a client error from your own code, throw an error with a 4xx statusCode and expose: true, such as those from fastify.httpErrors. Fastify’s own errors, whose code starts with FST_ (such as invalid JSON or a body that is too large), also keep their 4xx status. Other errors answer 500, even with a 4xx status (such as a database or search backend error escaping your route), so internal details don’t reach clients.

export class DepositFinalisedError extends Error {
statusCode = 409;
expose = true;
}

Build response bodies in your routes with the same helpers arocapi uses:

import { createError, createNotFoundError, ERROR_CODES } from 'arocapi';
const id = 'https://example.org/collection';
export const notFound = createNotFoundError('The requested collection was not found', id);
export const conflict = createError(ERROR_CODES.CONFLICT, 'The deposit is already finalised');

Pass Fastify’s prefix register option to mount arocapi under a path, for example /api. arocapi then answers unknown paths under that prefix with 404 NOT_FOUND. Without a prefix, unknown paths go to the not-found handler of the scope arocapi is registered in.