Plugin Architecture & Lifecycle Hooks

Katal plugins provide a modular way to package, distribute, and encapsulate reusable features across applications. A plugin can register dependency injection services, declare route groups, bind middleware, and execute asynchronous tasks across the application lifecycle.


1. Quick Start

import { Application } from "katal";
import type { KatalPlugin } from "katal";

// 1. Define plugin options
interface MetricsPluginOptions {
    prefix?: string;
    collectIntervalMs?: number;
}

// 2. Implement KatalPlugin contract
export const metricsPlugin: KatalPlugin<MetricsPluginOptions> = {
    name: "metrics-plugin",

    onRegister({ container }, options) {
        // Register services in DI container before boot
        container.singleton("metrics_prefix", () => options.prefix ?? "app_");
    },

    onBoot({ app }) {
        // Register routes during boot
        app.group("/metrics", (router) => {
            router.get("/", (ctx) => ctx.json({ status: "healthy", uptime: process.uptime() }));
        });
    },

    onReady() {
        console.log("Metrics collection started.");
    },

    onClose() {
        console.log("Flushing final metrics buffer on shutdown.");
    },
};

// 3. Register with application
const app = new Application({ port: 3000 });
app.registerPlugin(metricsPlugin, { prefix: "katal_" });

await app.listen();

2. Plugin Lifecycle Hooks

Katal executes plugin hooks across well-defined application lifecycle phases:

                  ┌──────────────────────┐
                  │   app.registerPlugin │
                  └──────────┬───────────┘
                             │
                             ▼
                  ┌──────────────────────┐
                  │     onRegister()     │  (Registers DI tokens, middleware)
                  └──────────┬───────────┘
                             │
                             ▼
                  ┌──────────────────────┐
                  │      app.boot()      │
                  ├──────────────────────┤
                  │       onBoot()       │  (Mounts routes, prepares adapters)
                  └──────────┬───────────┘
                             │
                             ▼
                  ┌──────────────────────┐
                  │     app.listen()     │
                  ├──────────────────────┤
                  │      onReady()       │  (Server listening, background pollers)
                  └──────────┬───────────┘
                             │
                             ▼
                  ┌──────────────────────┐
                  │      app.stop()      │
                  ├──────────────────────┤
                  │      onClose()       │  (Graceful cleanup, flush buffers)
                  └──────────────────────┘
Lifecycle Hook Execution Time Purpose
onRegister(context, options) Immediate upon calling app.registerPlugin Binds DI dependencies, registers named middleware, defines policies.
onBoot(context, options) During app.boot() Registers route groups, loads configuration, connects database clients.
onReady(context, options) Immediately after HTTP server begins listening Spawns background timers, WebSocket tunnels, or cache warmers.
onClose(context, options) During app.stop() Flushes memory buffers, closes network connections, cancels timers.

3. Real-World Example: Sentry Error Monitoring Plugin

Here is a production-grade plugin packaging error capture, correlation ID tagging, and automated teardown:

import type { KatalPlugin } from "katal";

export interface SentryPluginOptions {
    dsn: string;
    environment?: string;
}

export class SentryClient {
    constructor(private readonly dsn: string, private readonly env: string) {}

    captureException(err: Error, context?: Record<string, unknown>) {
        console.error(`[Sentry Alert] (${this.env}) ${err.message}`, context);
        // Post error to Sentry API...
    }

    async flush() {
        // Flush unsent events
    }
}

export const sentryPlugin: KatalPlugin<SentryPluginOptions> = {
    name: "sentry-error-monitor",

    onRegister({ container, app }, options) {
        const client = new SentryClient(options.dsn, options.environment ?? "production");
        container.instance(SentryClient, client);

        // Global error interceptor middleware
        app.use(async (ctx, next) => {
            try {
                return await next();
            } catch (err: any) {
                client.captureException(err, {
                    url: ctx.request.url,
                    method: ctx.request.method,
                    requestId: ctx.id,
                });
                throw err; // Allow standard Problem Details handler to respond with 500
            }
        });
    },

    async onClose({ container }) {
        const client = container.resolve(SentryClient);
        await client.flush();
    },
};

4. Plugins vs Service Providers: When to Use Which?

Consideration ServiceProvider Plugin
Primary Scope Core framework subsystems & low-level infrastructure bindings. Feature bundles, third-party integrations, and modular business domains.
Typical Tasks Binding interfaces to DB drivers, configuring Redis Streams, loading .env config. Attaching route groups, global error middleware, OpenAPI plugins, Webhooks.
Encapsulation Extends ServiceProvider class with register(), boot(), stop(). Object literal implementing KatalPlugin<TOptions> contract.
LIFO Teardown Standardized LIFO reverse order guarantee. Invokes onClose() sequentially across registered plugins.

See Also