Docs

Guide 07

Events and listeners

07. Events and listeners

Events are how Avelon gets extended. A third-party package registers listeners in a provider, so it never has to ask you to edit a controller.


Define an Event

// app/Events/PostPublished.ts
import { Event } from '@avelonjs/core'

export class PostPublished extends Event {
  constructor(
    readonly postId: string,
    readonly title: string,
  ) {
    super()
  }
}

Define a Listener

// app/Listeners/NotifySubscribers.ts
import { defineListener, mailers } from '@avelonjs/core'
import type { PostPublished } from '../Events/PostPublished'

export const NotifySubscribers = defineListener({
  delivery: 'queued', // 'sync' | 'after' | 'queued'
  queue: 'notifications',
  priority: 10, // lower runs first
  tries: 3,
  backoff: [10, 60, 300],
  async handle(event: PostPublished, context) {
    await mailers.mailer().send({
      to: 'editors@example.com',
      subject: `Published: ${event.title} (attempt ${context.attempt})`,
      text: `Post ${event.postId} is live.`,
    })
  },
})

The handler's parameter type names the event.

delivery: 'queued' makes these fields required:

  • queue
  • tries
  • backoff

reeve make:listener NotifySubscribers --event=PostPublished --queued writes this shape and registers it.

Register Listeners

// app/Providers/AppProvider.ts, inside registerApp()
Events.listen(PostPublished, [NotifySubscribers, IndexPostForSearch, WarmPostCache])
Events.subscribe(AuditSubscriber)
Events.listen('Post*', WildcardLogger)

Delivery Modes

ModeRunsRetriesSurvives function death
syncinline, before the action returnsnon/a
afterpost-response, same invocationnono
queuedin a workeryesyes

sync

sync is the default, because it's the only mode where a listener can affect the outcome.

after

after needs no infrastructure and is best-effort. Good for analytics and cache warming. Wrong for anything a user would notice missing.

For Next pages, server actions, and route handlers, after() runs the request's listeners and errands after the response finishes. That includes redirects and errors.

  • If a listener or errand throws, the adapter logs the failure and continues
  • Direct calls outside a Next request flush their own work before settling
  • Non-Next hosts and kernel tests still use finishResponse() for explicit delivery

queued

queued is durable and the right default for anything touching a third party.


Dispatch an Event

await Events.dispatch(new PostPublished(post))
// sync listeners run in priority order and are awaited, then queued listeners enqueue

await Events.dispatch(new PostPublished(post), { afterCommit: true })
// registers the dispatch for commit when called inside a transaction boundary

await Events.dispatchAfterResponse(new PostPublished(post))
// every listener runs post-response regardless of its declared mode

await Events.until(new PostPublishing(post))
// halts on the first non-null return and yields it

After Commit

With afterCommit: true, dispatch registers the event and returns while a commit boundary is active.

A commit boundary comes from:

  • the Postgres and Neon drivers
  • runInTransaction, when you create one yourself

Nested calls share the outer boundary.

The events dispatch after a successful commit. They're discarded on rollback or a failed commit. Without an active boundary, dispatch follows the event's configured delivery modes immediately.

When It Fails

  • If a sync listener throws during deferred dispatch, the transaction promise rejects after commit
  • Inside an active boundary, Events.until(event, { afterCommit: true }) rejects with Invalid

To get a result from until, call until(event) during the transaction, or call until after the transaction resolves.


Propagation

Sync listeners run ordered by priority. A listener halts the chain by returning false or by calling event.stopPropagation().

A halted chain does not enqueue the queued listeners behind it. That's what makes a veto mean something. Otherwise it'd be a suggestion that fires after the side effects were already scheduled.

The dispatcher can read event.isPropagationStopped(), so a controller can branch on the outcome.


Model Events

Model lifecycle hooks dispatch a ModelLifecycle event from @avelonjs/orm on the same bus. That makes Observers ordinary listeners.

The hooks:

creating  created  updating  updated  saving  saved  deleting  deleted  restored
Events.listen(
  ModelLifecycle,
  defineListener({
    handle(event: ModelLifecycle) {
      if (event.modelName === 'Post' && event.hook === 'deleting') return false
    },
  }),
)

A listener that returns false aborts the write on these hooks:

  • saving
  • creating
  • updating
  • deleting

Because it's the same bus, a package can observe your models without you registering anything model-specific.


Serialization

Queued listeners run in a worker with no request, no cookies, and no actor.

The default serializer copies the event's own fields into the queued payload as JSON. The worker restores them onto the event class.

Put identifiers on the event instead of models.

There are 2 consequences that belong in the docs instead of a stack trace:

  1. A queued listener loads the record when it runs, so it sees the record as it exists then, not as it was when dispatched.
  2. A worker has no actor, so Gate.actor() is null. Anything authorization-sensitive must receive an explicit actor id on the event.

Failure

When a listener throws:

  • sync - bubbles into the request, and the action fails
  • after - logged, the request already returned, no retry
  • queued - retried per tries and backoff. Then it's kept with its payload in the queue driver's failed storage, or on the process job board when no queue is bound

Discoverability

An event-driven codebase is only legible if you can answer "what happens when this fires" without grepping. Packages register listeners too, so this command isn't optional:

reeve event:list
EVENT          LISTENER           DELIVERY  QUEUE          TRIES  PRIORITY
PostPublished  NotifySubscribers  queued    notifications  3      10

It loads the app and prints every registered listener, including the ones a third-party package registers at boot. Each row shows:

  • event
  • delivery mode
  • queue
  • tries
  • priority

--json prints the same rows for scripts.