Skip to content

Documentation · IGNIS

The Application Class ​

The Application class is the root of an IGNIS server. It owns the IoC container, runs the boot sequence that registers your classes, serves HTTP on Bun, and stops cleanly. You extend BaseApplication, implement five hooks, and describe the rest in one config object.

Deep Dive: See Application Reference for technical details.

Creating an Application ​

Extend BaseApplication and implement the hook methods:

typescript
// src/application.ts
import {
  BaseApplication,
  IApplicationConfigs,
  IApplicationInfo,
  ValueOrPromise,
} from "@venizia/ignis";
import AutoArtifacts from "@venizia/ignis-boot/auto";
import packageJson from "./../package.json";

// Application configurations
export const appConfigs: IApplicationConfigs = {
  host: process.env.APP_ENV_SERVER_HOST,
  port: +(process.env.APP_ENV_SERVER_PORT ?? 3000),
  path: {
    base: process.env.APP_ENV_SERVER_BASE_PATH ?? "/",
    isStrict: true,
  },
  debug: {
    shouldShowRoutes: process.env.NODE_ENV !== "production",
  },
  // Registers every decorated datasource, component, repository, service and controller
  artifacts: AutoArtifacts,
};

// Main Application class
export class Application extends BaseApplication {
  override getAppInfo(): ValueOrPromise<IApplicationInfo> {
    return packageJson;
  }

  staticConfigure(): void {
    // e.g., this.static({ folderPath: './public' })
  }

  preConfigure(): ValueOrPromise<void> {
    // Setup a decorator cannot express, e.g. bind a value or an option
  }

  postConfigure(): ValueOrPromise<void> {
    // Logic to run after everything is configured
  }

  setupMiddlewares(): ValueOrPromise<void> {
    // Add any custom application-wide middlewares
  }
}

Application Lifecycle ​

The IGNIS application has a well-defined lifecycle, managed primarily by the init(), start() and initialize() methods.

MethodDescription
constructor(opts)Initializes the application, sets up the Hono server (OpenAPIHono), and reads the runtime (Bun). The Application extends Container (IoC container).
init()Registers the core bindings, including CoreBindings.APPLICATION_INSTANCE. Call it before start().
start()The main entry point. It calls initialize(), sets up middlewares, mounts the root router, and starts the HTTP server.
stop()Runs the post-stop hooks, stops the server (Bun.serve().stop()), then closes every datasource the boot configured, so no pool, socket or PGlite instance outlives the application. Each datasource gets dataSourceCloseTimeoutMs (default 10 s) to close.
initialize()Orchestrates the entire setup process, calling the various configuration and registration methods in the correct order.

WARNING

start() does not call init() for you, and nothing else does either. init() is the only caller of registerCoreBindings(), which binds CoreBindings.APPLICATION_INSTANCE. Built-in components inject that key (the request tracker is registered first), so an application started without init() throws Binding key: @app/instance is not bounded in context! on the first component resolution.

typescript
const application = new Application({ scope: 'MyApp', config: appConfigs });
application.init();
await application.start();

BaseApplication declares five abstract hook methods, so a subclass implements all of them (an empty body is fine). These are the places you write application-specific setup code.

Hook MethodPurpose
getAppInfo()Return application metadata, usually from package.json. Read by the OpenAPI docs and the health check.
staticConfigure()Configure static file serving. Called before preConfigure().
preConfigure()Register what the artifact index cannot express - registry calls, hand-made bindings. Classes come from configs.artifacts, see Registering artifacts.
postConfigure()Perform actions after all resources have been configured and instantiated. Note: do not bind new datasources, components, or controllers here -- they will not be auto-configured.
setupMiddlewares()Add custom application-level middlewares to the Hono instance. Called after initialize() completes.

Lifecycle Diagram ​

This diagram shows the sequence of operations during application startup. initialize() runs a boot sequence of sixteen named steps, always in this order.

init()                                   ← You call this. Binds CoreBindings.APPLICATION_INSTANCE
  │
  ▼
start()
  │
  ▼
initialize()
  │
  ├─►  1. printStartUpInfo               (application name, version, environment)
  ├─►  2. validateEnvs
  ├─►  3. registerDefaultMiddlewares     (CORS, request id, body limit, error handler, 404, request tracker,
  │                                        contextStorage() when asyncContext.enable, favicon)
  ├─►  4. staticConfigure                ← Override hook
  ├─►  5. registerArtifacts              (registers the index named by configs.artifacts)
  ├─►  6. preConfigure                   ← Override hook
  ├─►  7. hydrateSecrets                 (builds the provider from registerSecrets(), merges its hydrate bundles into the environment)
  ├─►  8. registerConfigurations
  ├─►  9. registerDataSources
  ├─► 10. registerComponents
  ├─► 11. registerContributedDataSources (datasources a component added)
  ├─► 12. wireSecretRotatables           (subscribes rotatable datasources to rotation)
  ├─► 13. registerControllers            (REST + gRPC transport components)
  ├─► 14. postConfigure                  ← Override hook
  ├─► 15. verifyBindings                 (only when bootChecks.binding.doVerify is on)
  └─► 16. validateScopeFilterSupport
  │
  ▼
setupMiddlewares()                       ← Override hook
  │
  ▼
Mount Root Router (server.route(basePath, rootRouter))
  │
  ▼
Start HTTP Server (Bun.serve)
  │
  ▼
executePostStartHooks()

The step names above are the vocabulary you target with BootSequence.insertAfter. They live on ServerBootSteps, which extends the kernel's BootSteps.

Configuration ​

Application configuration is passed to the BaseApplication constructor via an IApplicationConfigs object.

Configuration Options ​

OptionTypeDefaultDescription
hoststring'localhost'The host address. Falls back to HOST or APP_ENV_SERVER_HOST env vars.
portnumber3000The port to listen on. Falls back to PORT or APP_ENV_SERVER_PORT env vars; a value outside 0-65535 is skipped. 0 asks the OS for a free port, and getServerPort() returns the real one.
projectRootstringprocess.cwd()The directory that holds node_modules at run time. Never __dirname inside a compiled binary.
path.basestringrequiredThe base path for all application routes (e.g., /api). An empty string mounts the application at the root; a value that is not a string makes the constructor throw.
path.isStrictbooleantrueThe type requires path to carry it; an omitted value at run time means true. When true, /users and /users/ are different routes. Set false to answer both, and declare routes without a trailing slash: under false, a route declared as /users/ is unreachable.
debug.shouldShowRoutesbooleanfalseIf true, prints all registered routes to the console on startup.
faviconstring'🔥'An emoji to be used as the application's favicon.
artifactsTArtifactIndexInputundefinedThe generated artifact index (or several) to register before preConfigure(). See Registering artifacts.
asyncContext.enablebooleantrue on BaseApplication, false on RestApplication and WorkerApplicationEnable Hono's async context storage (powered by contextStorage()). Only a server application reads it; a Worker has no async context store, so true there changes nothing.
transportsTControllerTransport[]['rest']Controller transports to enable. Add 'grpc' for gRPC support.
error.rootKeystringundefinedOptional root key for error response wrapping.
error.environmentstringprocess.env.NODE_ENVThe ambient environment name. Set it where there is no process.env, such as a browser Worker. BaseApplication ignores it and reads process.env.NODE_ENV.
middlewares.corsobjectundefinedCORS options. Installed first, so early framework responses such as the body-limit 413 carry the headers.
middlewares.bodyLimitobject5 MiB on every routeRequest body limit. Installed right after the request id, ahead of every other middleware. Setting it replaces the default; enable: false removes it; a route sets its own with BodyLimits.route.
server.idleTimeoutnumberBun's defaultSeconds a connection may sit idle before Bun closes it. Bun caps it at 255. Passed to Bun.serve.
server.maxRequestBodySizenumberBun's defaultLargest request body, in bytes. Passed to Bun.serve.
discoverArtifactsbooleanfalseRegisters every decorated class the application imports, with no index. With artifacts too, the union registers.
bootChecksobjectundefinedBoot-time checks: binding.{ doVerify, allowManual, allowOverride } and allowDerivedKeyCollision. Without binding, nothing is verified. See Registering artifacts.
dataSourceCloseTimeoutMsnumber10_000How long stop() waits for one datasource to close. 0 waits without limit.

Example Configuration ​

typescript
import { ControllerTransports } from '@venizia/ignis';

export const appConfigs: IApplicationConfigs = {
  host: "0.0.0.0",
  port: 3000,
  path: {
    base: "/api",
    isStrict: true,
  },
  debug: {
    shouldShowRoutes: true,
  },
  transports: [ControllerTransports.REST, ControllerTransports.GRPC],
};

Registering Resources ​

Decorate each class and set artifacts: AutoArtifacts in the application config. IGNIS registers every decorated class before preConfigure() runs. See Registering artifacts.

DecoratorMarksBinding Scope
@configuration()A typed configuration class, registered firstSingleton
@datasource({ ... })A database connectionSingleton
@component()A reusable moduleSingleton
@repository({ model, dataSource })Data accessTransient
@service()Business logicTransient
@controller({ path })API endpointsSingleton

Registering by hand ​

preConfigure() is for what a decorator cannot express. The this.dataSource(...), this.component(...), this.repository(...), this.service(...) and this.controller(...) methods still work as an escape hatch. Inside preConfigure() or postConfigure() they fail when configs.artifacts is set and bootChecks.binding.allowManual is false.

All of them accept an optional second parameter to customize the binding key:

typescript
// Default binding (key: 'controllers.UserController')
this.controller(UserController);

// Custom binding key
this.controller(UserController, {
  binding: { namespace: 'controllers', key: 'CustomUserController' }
});

Registration order for decorated classes:

  1. Configurations
  2. DataSources (database connections)
  3. Components
  4. Repositories (depend on DataSources)
  5. Services (depend on Repositories)
  6. Controllers (depend on Services)

Deep Dive: See Dependency Injection for how registration and injection work together.

Runtime Support ​

IGNIS runs on Bun >= 1.4 only. start() checks the runtime first and throws IGNIS requires Bun >= 1.4 (running on <runtime>) on any other one, before it touches a hook, a datasource or a socket. The server is Bun.serve:

typescript
Bun.serve({ port, hostname, fetch: server.fetch })

To commit the artifact index instead of using the Bun plugin of AutoArtifacts (@venizia/ignis-boot/auto), run ignis-artifacts generate and pass the result as configs.artifacts. See Registering artifacts.

Post-Start Hooks ​

Register hooks that execute after the HTTP server has started:

typescript
this.registerPostStartHook({
  identifier: 'cache-warmup',
  hook: async () => {
    // Warm up caches, start background jobs, etc.
  },
});

Graceful Shutdown ​

Nothing stops the application on SIGTERM or SIGINT by itself. Call installShutdownSignals() after start() to stop it, then exit, when the process is asked to end (a container stop, Ctrl-C):

typescript
const application = new Application({ scope: 'MyApp', config: appConfigs });
application.init();
await application.start();

const uninstall = application.installShutdownSignals({ timeoutMs: 20_000 });
// later, if you need to take the handlers off again: uninstall();
OptionDefaultMeaning
signals['SIGTERM', 'SIGINT']The signals that start a shutdown
timeoutMs15_000A shutdown that takes longer is force-exited with code 1
exitprocess.exitWhat ends the process; replace it in a test or a host that exits differently

It calls stop() once: a second signal while it runs is ignored. The process exits 0 when stop() finishes, and 1 when it throws or hits the timeout. Calling installShutdownSignals() again returns the same uninstall function and adds no listener. It is not installed unless you call it, and it exists on ServerApplication only, so a browser Worker host never gets process signal handlers.

A post-stop hook runs before the server stops. Register one with registerPostStopHook({ identifier, hook }), the same shape as registerPostStartHook.

Static File Serving ​

Serve static files:

typescript
staticConfigure(): void {
  this.static({ restPath: '/public/*', folderPath: './public' });
}

Uses hono/bun serveStatic.

See Also ​