Oak

Install Kilpi for Oak


Install and setup Kilpi

Install Kilpi and setup your Kilpi instance by following the quickstart guide.

export const Kilpi = createKilpi({ ... })

Handle unauthorized errors from .assert()

The .assert() method throws an error when authorization is denied. Oak surfaces errors via ctx.throw, so the global onUnauthorizedAssert handler requires access to ctx. One way to achieve this is using AsyncLocalStorage as shown below.

app.ts
import { AsyncLocalStorage } from "async_hooks";
// Create an AsyncLocalStorage which can provide the `ctx`
export const ctxStorage = new AsyncLocalStorage();
// Provide the `ctx` in a middleware -- all code running inside
// this block has access to `const ctx = ctxStorage.getStore()`.
app.use(async (ctx, next) => {
await ctxStorage.run(ctx, async () => {
await next();
});
});
kilpi.ts
import { ctxStorage } from "./app";
export const Kilpi = createKilpi({
// ...,
async onUnauthorizedAssert(decision) {
// Access the context if available
const ctx = ctxStorage.getStore();
if (!ctx) return;
// Optionally customize behavior based on the decision
switch (decision.reason) { ... }
// By default, throw a HTTP 403 Forbidden exception
ctx.throw(403, decision.message);
}
})