> For AI agents: the complete documentation index is available at https://navios.tech/llms.txt, the full documentation bundle is available at https://navios.tech/llms-full.txt.

# Plugins

A plugin packages setup that an application would otherwise do by hand: providers, interceptors, error mappers, extra routes and shutdown work. `@navios/openapi`, `@navios/otel` and `@navios/adapter-xml` are plugins. There is one plugin shape.

## Defining a plugin

This plugin counts requests per route and status, and serves the counts at `/metrics`. The registry and the interceptor are ordinary services:

```ts title="metrics.plugin.mts"
import { builder } from '@navios/builder'
import {
  Controller,
  definePlugin,
  Endpoint,
  inject,
  Injectable,
  InjectionToken,
  Module,
} from '@navios/server'

import type { Interceptor, RequestContext, RouteResult } from '@navios/server'

export interface MetricsOptions {
  prefix: string
}

const MetricsOptionsToken = InjectionToken.create<MetricsOptions>('MetricsOptions')

@Injectable()
class MetricsRegistry {
  private readonly options = inject(MetricsOptionsToken)
  private readonly counts = new Map<string, number>()

  count(route: string, status: number | undefined) {
    const key = `${this.options.prefix}_requests{route="${route}",status="${status}"}`
    this.counts.set(key, (this.counts.get(key) ?? 0) + 1)
  }

  render() {
    return [...this.counts].map(([key, value]) => `${key} ${value}\n`).join('')
  }
}

@Injectable()
class MetricsInterceptor implements Interceptor {
  private readonly registry = inject(MetricsRegistry)

  intercept(ctx: RequestContext, next: () => Promise<RouteResult>) {
    ctx.onFinish(() => this.registry.count(ctx.route.path, ctx.responseStatus))
    return next()
  }
}
```

The plugin wires them into an application:

```ts title="metrics.plugin.mts"
export const metricsPlugin = definePlugin({
  name: 'metrics',
  setup(api, options: MetricsOptions) {
    api.provide(MetricsOptionsToken, { value: options })
    api.intercept(MetricsInterceptor)
    api.addModule(MetricsModule) // defined below
    api.onShutdown(() => {
      // flush to wherever the counts go
    })
  },
})
```

`definePlugin` returns a function. Calling it with options gives a plugin instance:

```ts
const app = await NaviosFactory.create(AppModule, {
  adapter: defineFastifyEnvironment(),
  plugins: [metricsPlugin({ prefix: 'api' })],
})

// or, before init()
app.usePlugin(metricsPlugin({ prefix: 'api' }))
```

A plugin whose `setup` declares no options is called without arguments: `app.usePlugin(csvPlugin())`. One whose options are all optional may be as well. `usePlugin` throws once `init()` has been called.

## The plugin definition

| Field                 | Meaning                                                                                                                                                       |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`                | Unique name. One plugin registered twice with equal options is set up once. The same plugin with different options, or two plugins of one name, fail `init()` |
| `dependsOn`           | Names of plugins that must be set up before this one                                                                                                          |
| `setup(api, options)` | Called once during `init()`. May be asynchronous                                                                                                              |

Plugins are set up in dependency order, whatever order they were registered in. A dependency that is not registered, or a cycle between plugins, fails `init()` with a message naming the plugin.

## The plugin API

`setup` runs after the application's transports, and so the HTTP adapter, have been created and before modules are loaded. `provide` and `decorate` apply at once, everything else at its point of `init()`, so a plugin does not choose a stage. All of them belong into `setup` and throw afterwards; `api.transport()` and `api.container` work at any time.

| Call                              | Effect                                                                                                                                                                                                                                                             |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `api.provide(token, impl)`        | Supplies or replaces a provider. `impl` is a class, `{ value }`, `{ class, scope? }`, `{ factory, scope? }` or `{ existing }`. It wins over modules; what the application provides itself [stays](https://navios.tech/docs/server/essentials/modules.md#providers) |
| `api.decorate(token, fn)`         | Wraps every instance of a service after it is built. `fn` receives the instance and returns the one to use                                                                                                                                                         |
| `api.intercept(InterceptorClass)` | Adds an interceptor around every handler, on every [transport](https://navios.tech/docs/server/guides/other-transports.md)                                                                                                                                         |
| `api.addModule(ModuleClass)`      | Adds a module, and so its routes, to the application. Its providers are defaults that a module of the application overrides                                                                                                                                        |
| `api.transport(httpTransport)`    | The application's HTTP transport, or `undefined` when it has none. See [The HTTP transport](#the-http-transport)                                                                                                                                                   |
| `api.onBootstrap(hook)`           | Runs after routes are compiled and before the server listens                                                                                                                                                                                                       |
| `api.onShutdown(hook)`            | Runs during `close()`, in reverse registration order. The hook receives the signal name, if any                                                                                                                                                                    |
| `api.container`                   | The DI container                                                                                                                                                                                                                                                   |

Providers are described in [Providers](https://navios.tech/docs/di/essentials/providers.md), interceptors in [Guards and interceptors](https://navios.tech/docs/server/essentials/guards-and-interceptors.md) and error mappers in [Errors](https://navios.tech/docs/server/essentials/errors.md).

## The HTTP transport

Everything in the table above works in any application, with or without HTTP. What belongs to HTTP is reached through the transport:

```ts
import { definePlugin, httpTransport } from '@navios/server'

export const myPlugin = definePlugin({
  name: 'my-plugin',
  setup(api) {
    const http = api.transport(httpTransport)
    if (!http) {
      throw new Error('my-plugin needs the HTTP transport.')
    }
    // ...
  },
})
```

| Call                                | Effect                                                                      |
| ----------------------------------- | --------------------------------------------------------------------------- |
| `http.intercept(InterceptorClass)`  | Adds an interceptor around every route, and around nothing else             |
| `http.mapError(ErrorClass, mapper)` | Maps an error class to a response, like `app.mapError`                      |
| `http.encoder(kind, encoder)`       | Registers a [response encoder](#response-encoders) for a custom result kind |
| `http.routes()`                     | Every route. Complete from `api.onBootstrap` on                             |
| `http.adapter`                      | The adapter instance                                                        |

An interceptor that reads the request, such as its headers or path, is registered with `http.intercept`. One registered with `api.intercept` also runs for the handlers of other transports and receives their contexts.

## Contributing routes

A plugin adds routes by adding a module. The module, its controller and its endpoint declaration are written like any other; a plugin usually has its own `builder()` because it does not know the application's.

```ts title="metrics.plugin.mts"
const api = builder()

export const getMetrics = api.declareEndpoint({
  method: 'GET',
  url: '/metrics',
  response: 'text',
})

@Controller()
class MetricsController {
  private readonly registry = inject(MetricsRegistry)

  @Endpoint(getMetrics)
  metrics() {
    return this.registry.render()
  }
}

@Module({ controllers: [MetricsController] })
class MetricsModule {}
```

Routes added this way get the application's global prefix, pass through application-level interceptors and appear in `app.routes()`.

`api.onBootstrap` is where a plugin looks at the finished application. Its route list includes routes added by other plugins, because it is built after every `setup` has run:

```ts
api.onBootstrap(async () => {
  const registry = await api.container.get(MetricsRegistry)
  for (const route of http.routes()) {
    registry.count(route.path, 0) // start every route at a known series
  }
})
```

## Using the native server

`http.adapter` is typed as the adapter-neutral `HttpAdapter`, whose `server` is `unknown`. A plugin written for one adapter narrows it:

```ts
import { definePlugin, httpTransport } from '@navios/server'

import type { FastifyAdapter } from '@navios/adapter-fastify'

export const poweredBy = definePlugin({
  name: 'powered-by',
  setup(api) {
    const { server } = api.transport(httpTransport)!.adapter as FastifyAdapter
    server.addHook('onSend', async (_request, reply) => {
      reply.header('x-powered-by', 'navios')
    })
  },
})
```

Registering a Fastify plugin works the same way: `await server.register(somePlugin)` in an `async setup`. On Bun the native server does not exist until `listen()`, so `http.adapter.server` throws during `setup`.

## Response encoders

The server knows how to write six kinds of result: `json`, `text`, `blob`, `stream`, `sse` and `empty`. An encoder converts a result of another kind into one of those, which lets a package add a response format without touching the adapters.

A handler produces a custom kind with `result(kind, body)`, usually behind a helper the package exports:

```ts title="csv.plugin.mts"
import { definePlugin, httpTransport, result } from '@navios/server'

export const csv = (rows: string[][]) => result('csv', rows)

export const csvPlugin = definePlugin({
  name: 'csv',
  setup(api) {
    api.transport(httpTransport)!.encoder('csv', (value, ctx) => ({
      ...value,
      kind: 'text',
      headers: { ...value.headers, 'content-type': 'text/csv; charset=utf-8' },
      body: (value.body as string[][])
        .map((row) => row.join(ctx.query.separator === 'semicolon' ? ';' : ','))
        .join('\n'),
    }))
  },
})
```

The endpoint is declared with `response: 'text'`, `'stream'` or `'blob'`, and the handler returns the helper's value:

```ts
// exportUsers: GET /reports/users, response: 'text'
@Endpoint(exportUsers)
exportUsers() {
  return csv([
    ['id', 'name'],
    ['1', 'Ada'],
  ])
}
```

- An encoder runs inside the pipeline: after the handler's value has become a result, and before interceptors exit. It receives the request context, and an error it throws is mapped to a response like any other.
- `result()` also accepts `{ status, headers }` as a third argument.
- There is one encoder per kind; registering a second one for the same kind replaces the first.
- Encoders apply to route results only, not to the not-found response.

`@navios/adapter-xml` is built this way; see [XML responses](https://navios.tech/docs/server/adapters/xml.md).
