Skip to content
You're viewing documentation for v0.6.5. It may be out of date.Go to latest
Email SDK
Esc
↑↓navigate↵open⌘Jpreview
On this page

Create your first plugin

Build an audit-log plugin end to end, with middleware that records every send and a typed client extension that exposes the log.

This guide builds a real plugin from scratch: an audit log that records the outcome of every send and exposes the entries through a typed email.auditLog property. Along the way you use the two plugin capabilities that matter most, middleware for the send pipeline and extendClient for typed client extensions.

A plugin is a plain object: { id, adapters?, hooks?, middleware?, extendClient? }. The full lifecycle is in writing plugins; exact types in the plugin API.

Define the entry shape and factory

Type the extension first. EmailPlugin<TExtension> is generic over what extendClient returns, which is what makes email.auditLog fully typed later.

Keep recipients and bodies out of the entry shape. An audit log should answer “did the receipt for order 42 go out, through which route?” without becoming a PII store. Put correlation data in send-scope metadata instead.

Record outcomes with middleware

Middleware runs on the send pipeline. afterSend fires once per successful delivery; onError fires when a route has exhausted its retries. Add both to the returned object:

Exceptions thrown from afterSend and onError are swallowed, so observers cannot break a send. If you want a plugin that blocks sends (policy checks, allow-lists), throw from middleware beforeSend, which runs before validation and may also transform the message.

Expose the log with extendClient

extendClient returns properties merged onto the client. The keys must not collide with built-in client members (send, adapters, …) or another plugin’s extension; collisions throw an EmailValidationError at createEmailClient time.

The complete plugin is the factory from step 1 with the middleware and extendClient blocks inside the returned object.

Mount it and use the typed extension

email.auditLog is typed. TypeScript infers the intersection of all plugin extensions from the plugins array, so email.auditLog.entries[0]?.status autocompletes.

Test it

Pair the plugin with the testing adapters to verify both paths:

bun test passes with no network and no credentials.

Rules of thumb

  • One stable id per plugin; make it configurable if users may mount two instances.
  • middleware.beforeSend for anything that blocks or transforms; afterSend, onError, and hooks for observation only.
  • Keep extendClient surfaces small, and never reuse built-in client member names.
  • Each factory call should own its state: two clients with two auditLogPlugin() instances must not share entries.

Next

Last updated on