@web-ts-toolkit/message-service
Template-driven messaging service for Mongoose + Express applications.
Installation
pnpm add @web-ts-toolkit/message-service mongoose express
Peer dependencies:
mongoose >= 8
express >= 5
Runtime: Node >=24. Use package-root named imports (or CommonJS
require('@web-ts-toolkit/message-service')); there is no default export or public
deep-import subpath.
Bundling note: handlebars and the workspace deps are bundled (tsup externals are only mongoose/express), so only mongoose + express are peers.
Highlights
- Message persistence schemas —
Message, MessageArchive, and MessageRequest schemas with timestamps, indexes, archiving, and idempotency reservations
- Schema factories —
buildMessageSchema(config?), buildMessageArchiveSchema(), and buildMessageRequestSchema() for per-app configuration
- Template engine — Handlebars interpolation for sender/receiver content
- Template registry — register and lookup templates by
templateCd (per-instance or global)
- Action system — validate permissions, run handlers, archive messages, send notifications
- Route factory — standalone Express routes for template-based creation and action handling
- Pluggable providers — email and payment providers are interfaces, not hard dependencies
- Idempotent create — bounded
clientRequestId scoped to the requester and template for double-submit protection
- Typed errors — exported service and registry errors with stable route status mappings
Quick Start
import express from 'express';
import mongoose from 'mongoose';
import {
buildMessageArchiveSchema,
buildMessageRequestSchema,
buildMessageSchema,
createMessageRoutes,
defaultRegistry,
MESSAGE_ARCHIVE_MODEL_NAME,
MESSAGE_MODEL_NAME,
MESSAGE_REQUEST_MODEL_NAME,
type MessageTemplate,
type MessageUser,
} from '@web-ts-toolkit/message-service';
const app = express();
app.use(express.json());
declare function resolveAuthenticatedUser(req: express.Request): MessageUser | undefined;
const myAuthMiddleware: express.RequestHandler = (req, res, next) => {
const user = resolveAuthenticatedUser(req);
if (!user) {
res.status(401).json({ message: 'authentication required' });
return;
}
(req as express.Request & { user: MessageUser }).user = user;
next();
};
await mongoose.connect('mongodb://localhost/mydb');
mongoose.model(MESSAGE_MODEL_NAME, buildMessageSchema());
mongoose.model(MESSAGE_ARCHIVE_MODEL_NAME, buildMessageArchiveSchema());
mongoose.model(MESSAGE_REQUEST_MODEL_NAME, buildMessageRequestSchema());
const myTemplate: MessageTemplate = {
templateCd: 'welcome.request',
type: 'request',
description: 'Welcome request',
senderContent: { title: 'Welcome {{name}}', long: 'Sent to reviewers', short: 'Sent' },
receiverContent: { title: 'Review {{name}}', long: 'Please review this request', short: 'Review' },
uiTemplate: 'default-message',
prepareMessage: async ({ user, payload }) => ({
fromUser: user._id,
toRoles: ['reviewer'],
payload,
// Content (`senderContent`/`receiverContent`) renders from `templateData`,
// not from `payload`. Map caller input here so `{{name}}` renders.
templateData: { name: String(payload.name ?? '') },
}),
actions: [
{
actionCd: 'approve',
name: 'Approve',
variant: 'primary',
sender: false,
receiver: true,
runHandler: async ({ actionAttemptId }) => ({ actionAttemptId }),
},
],
};
defaultRegistry.register(myTemplate);
const { router, service } = createMessageRoutes({
getModel: mongoose.model.bind(mongoose),
});
app.use('/api/messages', myAuthMiddleware, router.original);
Prerequisites for the flow above: Node >=24, mongoose >= 8, express >= 5,
and a MongoDB replica set (or sharded cluster) when you use clientRequestId
idempotency or transactional archival — standalone servers throw
MessageTransactionRequiredError instead of partially persisting. The auth
middleware above is required: routes resolve req._user || req.user and return
401 before any service, template, payment, model, or action effect when the
identity is missing or malformed.
Create a message and act on it (content renders from templateData):
const senderId = new mongoose.Types.ObjectId();
const reviewerId = new mongoose.Types.ObjectId();
const created = await service.createMessage({
templateCd: 'welcome.request',
user: { _id: senderId },
payload: { name: 'Ada' },
});
// `created` is `Array<IMessage | IMessageArchive>`; fresh creates resolve
// active documents only, while completed `clientRequestId` replays may mix in
// `IMessageArchive` records (narrow with `'archivedAt' in doc`).
const message = created[0];
if (!message || 'archivedAt' in message) throw new Error('expected an active message');
console.log(message.receiverContent.title); // 'Review Ada'
const listed = await service.getActions(String(message._id), 'receiver', {
user: { _id: reviewerId, roles: ['reviewer'] },
});
console.log(listed?.actions.map((action) => action.actionCd)); // ['approve']
For per-app template isolation, pass a custom TemplateRegistry:
import { TemplateRegistry } from '@web-ts-toolkit/message-service';
const registry = new TemplateRegistry();
registry.register(myTemplate);
const { router, service } = createMessageRoutes({
getModel: mongoose.model.bind(mongoose),
registry,
});
Independent applications in one process
Use separate connections/databases or disjoint collections, an explicit registry
per app, and matching schema/service model names. Model names alone do not isolate
collections: Mongoose normally derives collection names from model names. This is
separate-app configuration, not shared-collection tenant enforcement. Explicit
registries never fall back to defaultRegistry; configured connections never fall
back to global models. Direct archive() always requires the app's registry.
This standalone factory uses only root named imports. Call once per connection;
register trusted templates in each registry before serving requests. Register the
configured ${prefix}User model first if using default email lookup; a custom
directory resolver needs no User model. Email is disabled when no provider is passed.
import type mongoose from 'mongoose';
import {
MessageService,
TemplateRegistry,
buildMessageSchema,
buildMessageArchiveSchema,
buildMessageRequestSchema,
type EmailProvider,
type EmailRecipientResolver,
type PaymentProvider,
} from '@web-ts-toolkit/message-service';
export async function createIndependentMessaging(
connection: mongoose.Connection,
options: {
prefix: string;
partyStorage: 'nativeObjectId' | 'opaqueString';
registry: TemplateRegistry;
paymentProvider?: PaymentProvider;
emailProvider?: EmailProvider;
emailRecipientResolver?: EmailRecipientResolver;
},
) {
const modelNames = {
active: `${options.prefix}Message`,
archive: `${options.prefix}Archive`,
request: `${options.prefix}Request`,
user: `${options.prefix}User`,
};
const activeSchema = buildMessageSchema({
connection,
archiveModelName: modelNames.archive,
userModelName: modelNames.user,
emailNotifier: options.emailProvider?.sendNotification.bind(options.emailProvider),
emailRecipientResolver: options.emailRecipientResolver,
});
const archiveSchema = buildMessageArchiveSchema();
if (options.partyStorage === 'opaqueString') {
for (const schema of [activeSchema, archiveSchema]) {
schema.add({
fromUser: { type: String, default: null, trim: true, minlength: 1 },
toUser: { type: String, default: null, trim: true, minlength: 1 },
});
}
archiveSchema.add({
archivedBy: { type: String, default: null, trim: true, minlength: 1, index: true },
});
}
const Message = connection.model(modelNames.active, activeSchema);
const Archive = connection.model(modelNames.archive, archiveSchema);
const Request = connection.model(modelNames.request, buildMessageRequestSchema());
await Promise.all([Message.init(), Archive.init(), Request.init()]);
const service = new MessageService({
connection,
modelNames,
registry: options.registry,
paymentProvider: options.paymentProvider,
});
return { service, Message, Archive, Request, modelNames };
}
Create app A with partyStorage: 'nativeObjectId', app B with
partyStorage: 'opaqueString', distinct prefix/connections/registries/providers,
then mount each with createMessageRoutes({ service, getUser }). Each host's
getUser(req) maps its own authenticated request shape to MessageUser; list
through service.listMessages({ user }) and serialize with serializePublicMessage.
Both apps may use the same templateCd, textual requester ID, and clientRequestId
without sharing reservations. Pass the correct registry to direct document
archive(actionCd, actorId, registry); it is a trusted host primitive, not authorization.
String storage must cover both parties and archive archivedBy, with the
identity/migration policy below.
Transactions still require a replica set/sharded cluster. Idempotent creates skip
schema email hooks; standalone notifications can use each app's bound notifier and
optional custom directory.
Bounded installed-consumer compatibility
The packed consumer tests exercise Express 5.0.0 / Mongoose 8.0.0 and the
exact Express/Mongoose versions installed in this workspace (currently 5.x/9.x).
Both lanes compile root-import ESM/CommonJS NodeNext and Bundler consumers with
strict: true, skipLibCheck: false, and run the two-app MongoDB lifecycle in
both module formats. The minimum-runtime CI lane executes the installed consumers
on actual Node 24.0.0; newer Node may run build/install/TypeScript tooling.
This bounded check does not certify every intervening or future peer release.
MSGA-11 compatibility correction: schema constants now retain explicit portable
Mongoose schema types, rather than expanding Mongoose 9-only inferred generics in
the shipped declarations. Active/archive document _id is explicitly ObjectId
across Mongoose 8 and 9. Runtime schemas, bundling, exports and peer/runtime floors
are unchanged; no data migration is required.
Reproduce from the repository after installing build dependencies and Node 24.0.0:
mkdir -p _tmp-msga
git check-ignore _tmp-msga
export TMPDIR="$PWD/_tmp-msga"
export MESSAGE_SERVICE_CONSUMER_NODE="$(asdf where nodejs 24.0.0)/bin/node"
export MESSAGE_SERVICE_EXPECT_NODE=24.0.0
pnpm --filter @web-ts-toolkit/message-service... build
pnpm --filter @web-ts-toolkit/message-service exec vitest run --config ../../vitest.config.ts --fileParallelism=false test/message-service.packed-consumer.test.ts -t MSGA-11
Each lane prints exact resolved peers/types/compiler, build-tool and consumer Node,
MongoDB version and completed checks. MESSAGE_SERVICE_REPORT_DIR optionally saves
JSON evidence outside packed temp consumers. Without the runtime override, local
tests execute with their test-runner Node, whose version is reported explicitly.
API
createMessageRoutes(options)
Creates a standalone Express router with message template routes. Returns { router, service }. Mount the returned JsonRouter with router.original.
All user-facing routes require a resolved user with a valid _id (non-empty string or ObjectId; missing, null, empty, numeric, array, and plain-object ids return 401). By default, routes read req._user || req.user; pass authMiddleware and/or getUser to adapt your authentication stack. A request with no resolved user returns 401 before any service, template, payment, model, or action side effect. Hosts remain responsible for installing authentication, permission population, and CSRF protection before mounting these routes.
Custom extractors are preserved: getUser, getPermissions, and getIdentity receive the original Express request and their return values are passed through to MessageService. The route factory enforces the shared principal contract: getUser must return a user with a non-empty string or ObjectId _id and optional roles that are undefined or an array of strings before continuing. Malformed roles also return 401 before service/model lookup. See authenticated principals for getter/hydrated users and the action-handler snapshot.
| Option |
Type |
Description |
getModel |
(name: string) => Model |
Mongoose model getter |
paymentProvider |
PaymentProvider \| null |
Required for nonempty payment codes; optional for code-free items and replay |
onPaymentCompensationFailure |
(event) => void \| Promise<void> |
Optional hook called when expiring an uncommitted payment session fails |
onTransactionCleanupFailure |
MessageTransactionCleanupFailureObserver |
Best-effort diagnostics when a service-owned transaction's endSession() rejects |
adminRoles |
string[] |
Fallback roles when toUser is absent and toRoles is omitted or empty |
registry |
TemplateRegistry |
Custom template registry (default: defaultRegistry) |
actionLeaseMs |
number |
Action lease in ms (default: 30000) |
authMiddleware |
((req, res, next) => void)[] |
Custom middleware applied to all routes before route validation |
getUser |
(req) => MessageUser \| undefined |
Extract authenticated user (default: req._user \|\| req.user) |
getPermissions |
(req) => Record<string, boolean> |
Extract permissions (default: req._permissions \|\| {}) |
getIdentity |
(req) => Record<string, unknown> |
Extract identity (default: req._identity \|\| {}) |
adminPermissionKey |
string |
Permission key for admin read-only view of actions (default: 'is.admin') |
Routes:
POST /new/:templateCd — create message from template. Body: { ...payload, clientRequestId? }
GET /:id/actions/:usertype — get available actions (usertype is sender or receiver)
POST /:id/action/:actionCd — execute action (POST)
Route input validation happens before database or template lookup:
templateCd must be 1-128 letters, digits, dots, underscores, or hyphens.
actionCd must be 1-128 letters, digits, underscores, or hyphens.
id must be a 24-character hex MongoDB ObjectId string.
usertype must be sender or receiver.
clientRequestId, when present, must be a string, is trimmed by the service, must be non-empty after trimming, and must be at most 128 characters.
HTTP contract change: action mutation is POST-only. GET /:id/action/:actionCd is not registered and must not be used for state changes; callers should treat a GET response as not found or method-not-allowed depending on surrounding Express middleware.
Public message DTOs (MSGR-03 migration)
POST /new/:templateCd returns PublicMessageDto[] for both fresh creation and
completed replay. The shipped Node host's list endpoint returns the same DTOs in
its existing { success: true, data } envelope. Root named exports
serializePublicMessage, PublicMessageDto, PublicMessageParty, and
PublicMessageSource let custom HTTP adapters use this contract too: