Skip to Content
HeronJS v4 is now available.
Versionv4Migration Guide

Migrating to HeronJS v4 from v3

Upgrade all installed @heronjs/* packages together. This guide covers migration from v3 and earlier v4 releases to the 4.7.0 APIs.

Upgrading from 4.6 to 4.7

Upgrade all installed @heronjs/* packages together, then review these application-facing changes:

  • Add optional schema to HTTP Body/Queries or GraphQL Params decorators when validation is needed. Annotate parsed inputs with z.output<typeof Schema>; no-schema calls still pass input through.
  • Prefer schema over tRPC’s legacy input option for Zod. Move WebSocket options.schema to top-level schema. Do not supply both old and new forms. Test transforms, async refinements, and the validation error responses.
  • Replace @Guard({}) with a requirement on a verified identity claim. Repeated and inherited policies all apply, even when they constrain the same claim. Predicates and custom authorizers must return exactly true. Remove invalid policies rather than relying on truthiness or inherited properties.
  • Share one gatekeeper constructor and resolver instance across modules in an application. Conflicting declarations fail startup. Use separate applications for distinct authentication domains. Review GraphQL authentication for header, cookie, and string-valued session credentials.
  • Review WebSocket queue limits, ACP update limits, and MCP execution limits. Await notification/update sends and honor cancellation. MCP limits do not bound the SDK’s internal HTTP SSE output buffer.
  • Guard now returns a typed class/method decorator; remove casts previously needed for its unknown return type.

The 4.6.1 diagnostic improvements and 4.6.2 support for current datasource classes in @DataSources are included. Existing 4.6 object-argument APIs and Observable worker dispatch remain in use.

Upgrading from 4.5 to 4.6

4.6.0 replaces positional arguments in framework-owned APIs with typed objects. Upgrade every installed @heronjs/* package together and update both calls and callback implementations; the previous positional forms are not supported.

Previous callReplacement
logger.info(message, data)logger.info({message, data})
new Logger(target, options)new Logger({target, options}); new Logger() remains valid
logger.log(logMessage)logger.log({message: logMessage})
await threads.run(request, options)await firstValueFrom(threads.run({request, options}))
threads.run$(pool, task, input, options)threads.run({pool, task, input, options})
container.registerInstance(token, instance)container.registerInstance({token, instance})
container.register(token, provider, options)container.register({token, provider, options})
cache.set(key, value, ttl)cache.set({key, value, ttl})
datasource(Source, tenant) / mongo(Source, tenant)datasource({source: Source, tenant}) / mongo({source: Source, tenant}); SQL/CQL selectors follow the same pattern
setMetadata(key, target, value, property)setMetadata({key, target, value, property})
HttpResponseUtils.output(data, pagination)HttpResponseUtils.output({data, pagination})
@WebSocket(namespace, options)@WebSocket({namespace, options})
@OnMessage(event, options)@OnMessage({event, options}); ReceiveFrom uses the same shape
@MCP(path, options)@MCP({path, ...options})
@ACP(path, options)@ACP({path, options}), or {name, version, path, ...options}

Callback implementations must migrate too: Runnable.run({input, context}), worker setup({container, config}), tRPC methods ({input, context}), ACP createSession({request, context}) and prompt({request, context}), HTTP hooks ({request, response}), cache identity ({principal, request}), MCP token verification ({token, request}), protocol authorization ({guard, context}), and EBS stream logging ({message, data}). Native SDK callbacks, decorator argument binding and injected constructors keep their external signatures. Named parameter types are exported alongside the APIs; existing generic relationships remain checked.

ThreadRunParams is the union of ThreadRequestRunParams and ThreadTaskRunParams. A request dispatch cannot also specify pool, task or input. Explicit task dispatch requires the input property, even for input: undefined. run is the single dispatch method and returns a cold Observable<unknown>; run$ is removed. Each subscription submits a new job, and unsubscribing cancels it. Invalid calls report errors on subscription. Worker handlers may still return values, Promises or Observables. For async/await, import firstValueFrom from rxjs and use await firstValueFrom(threads.run(params)); awaiting run directly does not subscribe or execute the job. Validate emitted results across the worker boundary before use.

Rebuild application modules and worker definitions together. Use exported framework constants instead of hardcoded framework keys, and clear framework-managed caches during the upgrade. Application-defined tokens and standard TypeScript reflection keys keep their identity.

Upgrading from 4.3 to 4.5

  • In 4.4, borrow replaces the removed borrowResource export from @heronjs/common. In 4.6, call it as borrow({value, release, validate}); the optional callbacks retain lease cleanup and validation behavior.
  • In 4.5, replace datasource source.forTenant(id) with source.with({tenant: id}) for SQL, MongoDB and CQL. Replace the TenantDataSource type with ScopedDataSource and use DataSourceScopeOptions for scope options. Views share runtime ownership and copy their scope options without mutating the owner.
  • Since 4.3.3, Kafka MessagePayload.headers preserves header values alongside data. Handle missing headers and string, Buffer, or repeated values when routing messages.

Upgrading from 4.2 to 4.3

  • Replace listener subServer configuration with protocols. Unsupported top-level server settings are rejected; place HTTP configuration in options and protocol configuration in protocols.
  • Remove imports and plugin configuration for @heronjs/thread/tool and @heronjs/thread/tool/rollup. Compile task definitions as independently importable ESM and register their output URLs with app.threads(...) before startup.
  • Review application logging: data and error redaction is off by default. Use new Logger({options: {redact: true}}), DEFAULT_LOG_REDACTION, or custom paths when redaction is required. Message text remains readable in all modes.
  • Use public Logger methods directly. Remove application imports of logging registration helpers and acquireStdioLogging; framework stdio routing remains automatic.

See Logging, HTTP configuration, and Worker tasks.

Updating within 4.3

The 4.3.2 startup format remains in 4.7.0. Review any log parsing that depends on terminal startup output: component names are now grouped by kind, and lifecycle progress messages and count summaries are omitted. Handler mappings and protocol resource details remain available. See startup logging.

Upgrade checklist

  1. Move to Node.js 24.11 or newer, ESM, and TypeScript decorator metadata.
  2. Replace process-wide containers and import-time registration with owned applications and explicit modules.
  3. Separate application configuration, startup, listening, and shutdown.
  4. Replace Express middleware and native implementation imports with framework HTTP contracts and managed setup hooks.
  5. Update typed DI/metadata, datasource initialization, worker definitions, and result validation.
  6. Review Observable completion/cancellation, authentication, cache identity, and logging changes.
  7. Build and test your application against the exact coordinated version you intend to deploy.

Runtime and installation

Use "type": "module" in package.json. Compile with module: "NodeNext", a modern target such as ES2024, experimentalDecorators: true, and emitDecoratorMetadata: true. Import reflect-metadata before loading decorated application classes. Relative imports in compiled ESM use .js extensions.

CommonJS bundles, require exports, and CommonJS worker entries are removed. Keep worker definition files independently importable as compiled ESM. Install the protocol packages and optional database/broker drivers your application actually uses. For a complete HTTP starter, see Getting started.

Package entrypoints

Move these imports to the package root:

Removed subpathReplacement
@heronjs/core/sqlSqlDataSource, SqlSource, useSql, and sql from @heronjs/core
@heronjs/core/mongodbMongo datasource, decorator, option types, and useMongo/mongo from @heronjs/core
@heronjs/core/cqlCQL datasource, decorator, option types, and useCql/cql from @heronjs/core
@heronjs/core/cacheuseCache and cache from @heronjs/core
@heronjs/common/globalsImport @heronjs/common; its root already supplies global declarations

Datasource error/limit/tenant contracts also come from core. The old subpaths are removed, so update dynamic imports and module-resolution configuration as well as source imports. Earlier v4 packages may still require the subpaths; update imports when upgrading to 4.7.0.

Native hook return types and setup callbacks retain their actual SDK types. Consequently, core’s unified declaration file references knex, mongodb, and cassandra-driver, even in applications using only HTTP or one database. Install all three SDK packages in the build environment for strict declaration checking:

npm install --save-dev knex mongodb cassandra-driver

Keep any SDK used at runtime in production dependencies instead. Loading core registers hook definitions without loading database drivers, opening connections, or installing globals; application startup owns global installation. Database connections load their SDK on acquisition.

The remaining subpaths have independent consumers: @heronjs/common/thread supplies the worker DI bridge, @heronjs/thread/worker is the worker bootstrap, and task definitions are compiled with the normal application build. Other modules expose only their package roots.

Application ownership and startup

HeronJS.create() returns a fresh configurable application; it does not initialize providers or start listeners. Configure it first, then await start() for background/stdio work or listen() for HTTP. listen() may follow start() without restarting owned resources.

import 'reflect-metadata'; import {Module} from '@heronjs/common'; import {HeronJS} from '@heronjs/core'; @Module({}) class AppModule {} await using app = await HeronJS.create({module: AppModule}); await app.start(); // Resolve initialized providers and perform application work here. // Awaited disposal closes this application when the scope ends.

For a long-running HTTP entrypoint, retain the application until shutdown and await app.close(). An await using scope closes its application when that scope exits. Shutdown cancels owned executions and awaits protocol, worker, datasource, and container cleanup.

Declare providers, services, controllers, transporters, graphqls, rpcs, websockets, mcps, acps, and databases in module metadata as applicable. Imported modules retain explicit export visibility. Decorators declare metadata rather than mutating process-wide runtime registries.

Removed global state and typed replacements

Previous API or behaviorReplacement
CoreContainer, CoreRegistry, cached HeronApp.appUse the returned application’s container and registry; use createContainer() for standalone ownership. HeronApp.create constructs a fresh root.
Import-time AUTO_REGISTER, autoInjectable, registry decoratorsDeclare providers/services/controllers/transporters in @Module(...), or register them explicitly on an owned container. Decorators declare metadata.
Globals installed on globalThis, _, GlobalFunctions, global reflectorUse named imports and application-owned containers; current global hooks resolve application scope rather than a shared singleton.
Caller-selected resolve<T>('name')Use a constructor or new Token<T>('name'). String/symbol lookup returns unknown; validate it before use. Registration must match the token’s value type.
Untyped reflection keys and invented metadata result typesUse metadataKey<T>(), setMetadata(), and obtain()/obtain_prop(). Raw keys yield unknown. Typed mixin writers also enforce the key’s value type.
Generic UseConfig<T>(...)Pass a typed metadata key and its matching configuration to UseConfig({key, config}).
Caller-selected results on worker execution and dynamic CQRS lookupValidate the returned unknown value, for example with a schema. Local Reactive.call infers the result from its callable.
Loose ThreadMessage with optional fieldsUse ParentMessage or WorkerMessage, include the fields required by its variant, and validate incoming data before dispatch.
Implicit datasource creation and synchronous tenant accessAwait datasource initialization; tenant repository with(...) asynchronously returns its selected client. Application lifecycle owns cleanup.
Runtime error payload bagsRead code, message, cause, and isFatal; use ErrorOptions when wrapping errors. Do not return internal causes to clients.
Global EBS lookup helpers (usePublisher, useStreamer, useKafka, useNats, useAMQP)Declare messaging adapters and handlers in the module, then resolve/inject their application-owned registrations.
Arbitrary built-in extension stringsUse the closed built-in union, or {type: 'CUSTOM', name, event} for a custom extension declaration.
Fastify hook-name objectUse framework HttpHooks or options.setup with a disposable useHttp() handle. See HTTP and protocols.
Import-time PRODUCTION / HERON_CONTEXT valuesCall readEnvironment() at the configuration boundary. Use new Logger(); logging defaults require no setup call.
LimitedMap.get() assumed presentHandle T | undefined; falsy keys remain valid and are evicted correctly at capacity.

Typed tokens preserve the relationship between registration and resolution:

import {Token, createContainer} from '@heronjs/common'; interface Clock { now(): number; } const clock = new Token<Clock>('clock'); const container = createContainer(); container.registerInstance({token: clock, instance: {now: () => Date.now()}}); const timestamp: number = container.resolve(clock).now(); await container.dispose();

Externally supplied instances remain externally owned. Use registerOwnedInstance or onDispose when the container should clean them up. Preserve the exported GATEKEEPER and GATEKEEPER_RESOLVER token identities when registering authentication dependencies.

Scoped hooks

Current v4 installs global hooks during start()/listen(), with application-scoped resolution. These replace the old process-wide mutable accessors. useX hooks remain available alongside container, datasource, http, sql, mongo, cql, and other noun acquisition functions. Read a lease through .value and release it with using or await using.

When only one application is running, it is the default outside an application scope. Multiple applications require an owning async scope or app.run(callback); unscoped lookup fails with AMBIGUOUS_CONTEXT. Package imports alone do not install globals. See Global hooks and resource ownership for acquisition and disposal rules.

HTTP and protocols

@heronjs/express retains its package name but uses Fastify 5. Express middleware configuration and assumptions about Express request/response objects must be replaced.

Previous usageCurrent usage
Express middlewares, app.use(...), and Express-specific request/reply methodsFramework HttpOptions.plugins, HttpHooks, interceptors, or native Fastify registration inside options.setup
Fastify-prefixed public types, native subpaths, standalone native constructors/factoriesHttpAdapter, HttpServer, and framework HttpRequest, HttpResponse, HttpOptions, HttpHooks; use typed leases for native customization
Engine hook-name objects in framework configurationHttpHooks.onRequest, beforeHandler, afterResponse, onReady, and onClose; native engine hooks belong in setup
Direct native request/reply fields such as .raw or .serverFramework request/reply views; validate body, params, and query before use
Engine-owned session property accessFramework session get, set, and delete
Separate Express mounts for GraphQL or tRPCRegister schema/procedure classes in module metadata; extensions share core’s HTTP listener
Listener-level MCP/ACP/WebSocket endpoint policyAuthentication, limits, and transport on the endpoint decorator; app.add() keeps shared server settings
runtime.transportExplicit MCP/ACP transport: 'stdio' plus runtime: {stdio: true}; otherwise HTTP

Use HTTP setup for managed engine access. Cookie/session plugins, parsers, and proxies must use Fastify-compatible integration. Borrowing an engine does not make the application code its owner.

Protocol handlers now receive framework request/reply views and protocol contexts. tRPC context has req, res, optional authContext, and signal; MCP uses McpContext with identity, signal, and SDK protocol access. Check the protocol examples in the release guide.

MCP/ACP endpoints default to HTTP independently. Only one endpoint can own stdio, and other HTTP endpoints can coexist. Remote MCP/ACP binding requires authentication or explicit public access and appropriate Host/Origin allowlists. WebSocket uses native browser WebSocket framing, not Socket.IO.

Cache and streaming routes

Replace @Cachable imports and usages with @Cacheable from @heronjs/common; the misspelled export is removed.

Configure private HTTP identity on each @Cacheable and @Evict decorator. Remove global HTTP cache configuration, manual group, and scope/private switches. Derive identity from a verified principal, including tenant, subject, and effective authorization; never use raw bearer tokens or unverified user IDs.

HTTP cache namespaces derive from registered route metadata. Use requestKey for request-derived variation; legacy value-based keys are for non-HTTP consumers. Guards execute even on cache hits, and eviction targets the resolved identity’s cached routes in the same controller. TTL is milliseconds. See Private caching.

Use @SSE for Observable/AsyncIterable streams, honor the request’s executionSignal, and avoid cache/eviction or manual-response decorators on an SSE method. Ordinary REST handlers consume only the first Observable value. See Server-Sent Events.

Datasources

Await initialization before use. Module-registered datasources initialize before dependent providers and are closed by the application. For standalone sources, call initialize() and own disposal yourself. Await asynchronous tenant repository with(...) calls.

Import SQL, MongoDB, and CQL datasources and hooks directly from @heronjs/core with backend-specific configuration. The unused NoSQL placeholder is removed. SQL needs Knex 3.2.10 or newer and mysql2 for MySQL/MariaDB; native SDK instances are obtained through typed acquisition hooks.

Prefer a source class or typed token for inference. String/default lookup returns unknown; a single registered string selects a named source, while an unregistered string selects a tenant on the default. Use a second argument to select a tenant explicitly. Multiple datasources require an explicit default for default lookup. Tenant views share pools without mutating the owner.

Previous v4 NoSQL APIs

4.2.0 removed the NoSQL model/repository/schema/migration layer introduced in 4.1. If upgrading through those versions, replace repository, withTenant, migrate, models, schema planners, and the model decorators Document, Field, Index, Table, Column, PartitionKey, and ClusteringKey. Lease values no longer expose migrate either. SQL repository APIs are separate from this NoSQL removal.

Use a managed connection for application-owned operations:

import {type MongoDataSource, useMongo} from '@heronjs/core'; async function findRecord(source: MongoDataSource, id: string) { await using connection = await useMongo({source: source}); return await connection.value.database.collection<{id: string}>('records').findOne({id}); }

For CQL, use await useCql({source: source}) and connection.value.client.execute(...). Replace withTenant with a tenant-selected lease, such as await mongo({source: 'records', tenant: 'tenant-a'}). Run migrations through application/deployment tooling and create CQL keyspaces before startup. See NoSQL connections for setup callbacks, constructor configuration, tenant selection, and client ownership.

Workers and dependency injection

Declare worker requests with @Task and register their exported module files with app.threads(...) before start() or listen(). The framework supplies the manager and creates each task module’s pool automatically. Keep task definitions separate from executable bootstrap.

Use utility decorators such as @Provider, @Repository, and @Dao for application dependencies. Compile with decorator metadata, use cloneable request data, validate worker results, and honor cancellation through RunContext.signal. Ordinary @Service classes stay on the main thread.

Messaging and reactive execution

Replace process-global EBS accessors with module-declared adapters and injected application-owned publishers/streamers. createBroker is internal: define broker classes with @MessagingAdapter(config) and register them in transporters. Select a class with @MessagingService({adapter: OrdersBroker}), @Subscribe({adapter: OrdersBroker, subject: 'orders'}), and @Publisher({subject: 'orders', options: OrdersBroker}) or @Streamer('orders', OrdersBroker). Kafka/AMQP subscriptions also specify their transporter. Use the transport enum as the second type parameter of MessagingPublisher/MessagingStreamer. Multiple decorated classes for the same transporter and normalized server URIs share one application-owned connection; different endpoints remain isolated. Standalone decorators remain supported for unambiguous broker selection.

Kafka requires @confluentinc/kafka-javascript 1.11.0 or newer. NATS streaming uses JetStream; processing failures or cancellation remain eligible for redelivery, so handlers must be idempotent. Messaging activation occurs after early provider initialization; do not publish from constructors. See Messaging.

Unary REST, GraphQL, tRPC, MCP/ACP, WebSocket, worker, and parent-RPC executions consume the first emission. Empty unary completion fails with EMPTY_RESULT; cancellation fails with CANCELLED. Finite lifecycle hooks and EBS consumers wait for completion. EBS streams, tRPC subscriptions, and worker services consume multiple emissions until completion or cancellation.

dispatchAndWait() now waits and propagates errors. Await finite hooks and observe errors on background executions. Promises need cooperative cancellation even when Observable subscriptions are disposed. Shared guard evaluation awaits asynchronous requirements/predicates and denies missing identity or failed evaluation. See Reactive execution.

Logging

Application message text is readable and data/error redaction is off by default. Use new Logger({options: {redact: true}}) or custom rules to enable data redaction. Keep private values out of message strings, which remain readable. See Logging for examples and output settings.

Renamed and removed contracts

Former contractReplacement
ILoggerLogWriter
ICollectionCollectionLike
IStackStackLike
IQueueQueueLike
IMapKeyValueStore
ICreatableCreatable
IActivatableActivatable
IDisposableDisposableResource
IConnectableConnectable
IExtensionExtensionLifecycle
IRegistryRegistryLike
ITransformTransform
IEventContextEventContextContract
IMessageBrokerMessageBroker
IResolverValueResolver
ICommandHandlerCommandHandler
IQueryHandlerQueryHandler
ICommandBusCommandBus
IQueryBusQueryBus
IDomainEventDomainEventMessage
IDomainEventHandlerDomainEventHandler
IEventBusEventBusContract
IContextContext
IDispatcherEventDispatcher
IAMQPHandlerAMQPChannelHandler
ArgumentReturnTypeScript ParameterDecorator
MethodReturnTypeScript MethodDecorator
Dictionary<T>TypeScript Record<string, T>
ICommand, IQueryobject; typed handler contracts retain their input relationships
IFunction, isFunctionalSupportedThe existing Interceptor contract and corrected isInterceptor predicate
Duplicate Resolver<R>AuthResolver<R>, extending the shared ValueResolver contract
String alias MessageBrokerstring for service broker identifiers; MessageBroker<T> now names the former IMessageBroker<T> contract

Any, TArgument, RequestInComing, ScopeOptions, and IFunctionalContext are removed; use concrete feature-owned contracts or validated unknown boundaries. Common’s Constructor<T> reuses thread’s ThreadConstructor<T>. Public error identities remain, with code, message, cause, and isFatal; avoid returning internal causes to clients. Handle LimitedMap.get() returning undefined.

Verify the upgrade

Build the application’s ESM output and check all public imports against the chosen package versions. Exercise startup and awaited shutdown, constructor injection, HTTP/agent authentication, private cache isolation, worker loading from deployed output, datasource tenant selection, and cancellation. Use disposable external databases/brokers for integration tests.

Last updated on