A static event contract should be the source of truth, and the Node.js process should refuse to start when a configured event name is outside that contract. Express middleware still validates every client message at runtime. Those are separate trust boundaries.
| Choice | Startup failure | Client input | Best fit |
|---|---|---|---|
| Shared static contract | Reject bad deployment config | Reject unknown or unauthorized events | Small fintech chat system with known event types |
| Runtime registry | Reject invalid registry entries | Validate against the loaded registry | Tenant-specific event catalogs |
| Accept names and ignore unknowns | Starts despite drift | Silently drops or mishandles input | Almost never appropriate for financial chat |
Recommendation: use a shared as const contract, validate configuration before listen(), then apply token-scoped authorization in middleware. It is boring, cheap to reason about, and keeps a typo from becoming a reconnect-only failure.
For a one-person SaaS, that matters more than building an elaborate event platform. I want the check to run on every deploy while I ship weekly. The differentiated work is the room experience; event-name bookkeeping is not.
How should Node.js validate event names against supported types?
Middleware runs after the process has started and a request has arrived. A misspelled configured name such as device.offine can therefore sit unnoticed until a client takes that path. Startup validation moves that failure to deployment, where the process can exit before it advertises readiness.
Fail fast.
That check does not make the client trustworthy. A reconnecting browser can replay stale intent, present a token for the wrong room, or send a real event name that its token is not allowed to publish. The server must validate three different things: the name exists, the payload matches the name, and the authenticated principal may perform that event in this room.
Keep those decisions apart.
In a fintech chat, message.create and device.status.changed may both be valid names. A customer-support token that may post a message should not automatically gain permission to publish device status. The allowlist answers "does this type exist?" Token scope answers "may this principal do it here?" Treating the first answer as the second turns a tidy type system into an authorization bug.
The awkward failure crosses several boundaries. Imagine a deploy config contains device.offine, while the browser correctly sends device.status.changed after reconnecting to a support room. Middleware accepts the browser's real name, yet any server component selecting configured handlers cannot find it. If the service merely logs and continues, the browser may retry an event that can never reach a handler. The user sees an old device badge beside a live conversation, support sees a valid room, and the startup typo remains far from the visible symptom. Rejecting the config before readiness collapses that chain into one actionable deployment error. Runtime authorization still runs because fixing the spelling says nothing about who may publish the update.
Make one contract do three jobs
A compact TypeScript object can drive compile-time types, startup checks, and runtime parsing. The example below deliberately keeps payload checks close to each event. There is no second list to drift.
const eventContract = {
"message.create": (value: unknown): value is { clientId: string; body: string } => {
if (!isRecord(value)) return false;
return typeof value.clientId === "string" && typeof value.body === "string";
},
"device.status.changed": (value: unknown): value is { deviceId: string; online: boolean } => {
if (!isRecord(value)) return false;
return typeof value.deviceId === "string" && typeof value.online === "boolean";
},
"room.resume": (value: unknown): value is { roomId: string; afterSequence: number } => {
if (!isRecord(value)) return false;
return typeof value.roomId === "string" &&
Number.isSafeInteger(value.afterSequence) &&
value.afterSequence >= 0;
}
} as const;
type EventName = keyof typeof eventContract;
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isEventName(value: string): value is EventName {
return Object.prototype.hasOwnProperty.call(eventContract, value);
}
function assertConfiguredEvents(values: readonly string[]): asserts values is readonly EventName[] {
const unknown = values.filter((value) => !isEventName(value));
if (unknown.length > 0) {
throw new Error(`Unsupported configured event names: ${unknown.join(", ")}`);
}
}
Run the assertion before opening the port. Configuration parsing should also reject an empty entry instead of quietly filtering it, because message.create,,room.resume usually means somebody made a deployment mistake.
import express, { type NextFunction, type Request, type Response } from "express";
const configuredEvents = (process.env.SUPPORTED_EVENTS ?? "")
.split(",")
.map((value) => value.trim());
if (configuredEvents.some((value) => value.length === 0)) {
throw new Error("SUPPORTED_EVENTS contains an empty event name");
}
assertConfiguredEvents(configuredEvents);
const app = express();
app.use(express.json({ limit: "32kb" }));
type Principal = {
subject: string;
roomIds: readonly string[];
publish: readonly EventName[];
};
type EventRequest = Request & { principal?: Principal };
function requireEvent(req: EventRequest, res: Response, next: NextFunction): void {
const name = req.body?.name;
const roomId = req.body?.roomId;
const payload = req.body?.payload;
if (typeof name !== "string" || !isEventName(name)) {
res.status(400).json({ error: "unsupported_event" });
return;
}
const principal = req.principal;
if (typeof roomId !== "string" ||
!principal?.roomIds.includes(roomId) ||
!principal.publish.includes(name)) {
res.status(403).json({ error: "event_not_allowed" });
return;
}
if (!eventContract[name](payload as never)) {
res.status(400).json({ error: "invalid_payload" });
return;
}
next();
}
app.post("/events", requireAuthenticatedPrincipal, requireEvent, acceptEvent);
app.listen(3000);
declare function requireAuthenticatedPrincipal(
req: EventRequest,
res: Response,
next: NextFunction
): void;
declare function acceptEvent(req: EventRequest, res: Response): void;
The as never call is a TypeScript limitation caused by indexing a map of differently narrowed predicate functions. It is contained after the key check. If that cast spreads into handlers, replace the predicate map with a discriminated schema abstraction rather than weakening request types across the app.
Notice the status split: malformed or unsupported input gets 400; a known event outside the principal's room or publish scope gets 403. Do not echo the token, its full claims, or sensitive payload data in either response. Logs can record a request correlation ID, the event name, and a coarse rejection reason.
Reconnects change the authorization question
A reconnect is not proof that the previous session remains authorized. Authenticate the new connection, derive its room membership and publish scopes again, and make resume a read operation anchored by a server-issued sequence position. The client can ask for afterSequence: 4182; it cannot declare that events through 4182 were accepted.
WebRTC illustrates the broader boundary even if the chat transport is not WebRTC: its specification defines connection state machinery, while the application still owns its signaling and application semantics. Transport recovery does not decide which business event a principal may publish. Keep protocol state and business authorization separate.
For delivery, attach a monotonically increasing sequence to accepted room events and persist the event before acknowledging it. On resume, return events after the last confirmed sequence that the newly authenticated principal is permitted to read. An idempotency key such as clientId prevents a retried message.create from creating two logical messages; a database uniqueness constraint should enforce that rule.
The order matters:
- Authenticate the current connection.
- Check room membership and event scope.
- Validate the payload for the known name.
- Deduplicate the client operation.
- Persist and assign the room sequence.
- Acknowledge acceptance.
This is where I would outsource undifferentiated work to established libraries already in the stack: token signature verification, schema parsing, and database constraints. The application-specific policy stays visible in a small function. Revenue per engineering hour favors code that can be inspected during an incident over a homegrown policy engine.
Test the boundary, not just the happy path
The first test should import the production startup assertion and prove a misspelling aborts boot. Add table-driven middleware tests for an unknown name, a known name with a bad payload, a valid name outside token scope, and a valid scoped event for the wrong room. Those four cases catch different failures; collapsing them into "request rejected" hides authorization regressions.
Then test reconnect behavior with two tokens: the original token and a replacement whose room access has been removed. The second token must not resume the room merely because it supplies a plausible sequence. Also send the same clientId twice around a simulated disconnect and verify that storage contains one logical message.
Make deployment readiness depend on startup completion. Emit a count of configured event types, never token contents, and alert on process-start failures plus sustained rejection rates by coarse reason. A burst of unsupported_event after a frontend deploy is useful evidence of contract drift. A burst of event_not_allowed may indicate stale clients or abuse, but the metric alone cannot distinguish them.
Two short rules help operationally. Never auto-add an event observed from a client. Never turn an unknown event into a no-op success.
When is a runtime registry the better choice?
Use the runner-up, a runtime registry, when event types are genuinely tenant-defined or installed independently of the application release. Validate the entire registry before marking the process ready, version each definition, and pin every accepted event to the definition version used to parse it. Cache invalidation then becomes part of the correctness model, so budget for stale-node and partial-rollout tests.
A static contract is better when the server owns a small, finite protocol. It gives TypeScript useful unions and makes code review straightforward. The registry earns its complexity only when independent change is a product requirement, not because a map looks unsophisticated.
Do not choose "accept and ignore" as a compatibility strategy. For chat rooms that must survive reconnects, a silent drop leaves the client unable to tell whether it should retry, advance its local cursor, or show failure. Explicit rejection gives both sides a stable result.
The final decision is narrow: fail deployment on an unknown configured name, reject unknown client names at the edge, and authorize every known name against fresh room-scoped claims. That preserves the useful part of a shared event contract without trusting the browser to enforce it.
References
- W3C, WebRTC 1.0: Real-Time Communication Between Browsers: https://www.w3.org/TR/webrtc/
Top comments (0)