@heywinit/chat-middleware
v0.1.0
Published
Middleware layer for the Vercel Chat SDK — global error handling and per-event context enrichment
Maintainers
Readme
@heywinit/chat-middleware
Middleware layer for the Vercel Chat SDK. Add global error handling, authentication, and context enrichment to your bot with a simple, familiar middleware pattern.
Features
- Global Interceptors: Run logic before every event handler (mention, message, action, etc.).
- Context Enrichment: Inject data into a shared context object accessible by all downstream handlers.
- Global Error Handling: Catch and handle errors across all bot interactions in one place.
- Ordered Execution: Middleware functions execute in the order they are registered.
- Async Support: Full support for
async/awaitin the middleware chain.
Installation
pnpm add @heywinit/chat-middlewareBasic Usage
import { applyMiddleware } from '@heywinit/chat-middleware';
applyMiddleware(bot, {
beforeEach: [
// Logger & Context Enrichment
async (ctx, next) => {
ctx.data.startTime = Date.now();
console.log(`[${ctx.type}] Processing event...`);
await next();
const duration = Date.now() - ctx.data.startTime;
console.log(`[${ctx.type}] Handled in ${duration}ms`);
},
// Simple Auth
async (ctx, next) => {
if (ctx.type === 'action' && !ctx.event.user.isAdmin) {
return; // Halt execution if not authorized
}
await next();
}
],
onError: async (err, ctx) => {
console.error('Bot Error:', err);
if (ctx.thread) {
await ctx.thread.post("Oops! Something went wrong.");
}
}
});Technical Details
applyMiddleware(bot, config)
This function wraps the bot's event registration methods to inject the middleware chain.
Middleware Context (MiddlewareContext)
Every middleware function receives a context object:
type: The event type (mention,message,subscribed,action,command).event: The raw event object from the underlying adapter.thread: TheThreadinstance (if applicable to the event).message: TheMessageinstance (if applicable to the event).data: A mutable record for passing information between middleware and into your bot's handlers.
The next() Function
Middleware must call await next() to continue to the next middleware in the chain or the final event handler. If next() is not called, the execution stops.
License
MIT
