The endpoint plugin is already included in @kilpi/core
. Apply the plugin in your Kilpi configuration as follows.
import { createKilpi, EndpointPlugin } from "@kilpi/core";
export const Kilpi = createKilpi({ getSubject, policies, plugins: [EndpointPlugin({ secret: process.env.KILPI_SECRET })]})
The secret can be included in the client bundle.
Usage
The endpoint plugin exposes the Kilpi.createPostEndpoint()
function which constructs a web-standard request-response handler function. You can integrate it with your framework of choice however you want. For example, with Next.js you would do the followings
// (req: Request) => Promise<Response>export const POST = Kilpi.createPostEndpoint();
See usage on client for how to set up KilpiClient
for calling the endpoint as below including batching, caching, and deduplication.
await KilpiClient.fetchIsAuthorized({ key: "documents:delete", resource: myDocument,});
SuperJSON serialization
The endpoint plugin uses SuperJSON for serializing the request and response bodies. This allows you to send complex data types such as dates, maps, sets, and other non-JSON-safe values in the request body and receive them in the response.
API reference
The API is designed for @kilpi/client
and is not optimized for calling manually, however it is possible.
Basic fetch example
The following is a basic example of how you can call the endpoint manually. It includes bearer authentication with secret
and SuperJSON.stringify
for serializing the request body.
import * as SuperJSON from "superjson";
function callKilpiApiEndpoint(body: RequestBody) { const response = await fetch(process.env.PUBLIC_KILPI_URL, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.PUBLIC_KILPI_SECRET}`, }, body: SuperJSON.stringify(body), });
if (!response.ok) throw new Error("Failed to call Kilpi API");
return (await response.json()) as ResponseBody;}
Request body schema
The request body is serialized with SuperJSON.
For batching purposes, the Kilpi API is always called with an array of items, each one of which has a unique requestId
and a type indicating the type of the request. Depending on the type, the request may require additional data.
type RequestBody = Array< | { type: "getIsAuthorized"; requestId: string; policy: string; // Policy key (e.g. "documents:create") resource?: any; // Optional resource } | { type: "getSubject"; requestId: string; }>;
Response schema
The response is always a corresponding array of items, with each item having a matching requestId
and data
attribute indicating the response data for that item.
type ResponseBody = Array<{ requestId: string; data: any }>;