Express Integration
The @bext/express package provides Express middleware that injects bext services into req.bext, plus a standalone client.
Installation
npm install @bext/express
Peer dependencies: express >= 4.0.0
Middleware
const app = express();
app.use(express.json());
app.use(bextMiddleware());
app.post("/api/articles", async (req, res) => {
const article = await db.articles.create(req.body);
// Invalidate cached article pages
await req.bext.cache.invalidateTag("articles");
// Push real-time event
await req.bext.realtime.publish("articles", { action: "created", article });
res.status(201).json(article);
});
app.listen(3000);
Custom Configuration
app.use(bextMiddleware({
baseUrl: "http://127.0.0.1:3061",
}));
Standalone Client
const bext = createBextClient();
await bext.cache.invalidateTag("products");
await bext.kv.set("counter", 42, { ttl: 3600 });
API Reference
Cache
The Express adapter includes an additional flush() method:
interface BextCache {
invalidateTag(tag: string): Promise<void>;
invalidatePath(path: string): Promise<void>;
flush(): Promise<void>; // Purge entire cache
}
KV Store
await req.bext.kv.set("user:prefs", { theme: "dark" }, { ttl: 86400 });
const prefs = await req.bext.kv.get("user:prefs");
await req.bext.kv.delete("user:prefs");
Queues
The Express adapter supports additional queue options:
// Enqueue with delay and retry limit
await req.bext.queue.push("notifications", payload, {
delay: 60, // delay 60 seconds before first delivery
maxRetries: 3, // retry up to 3 times before dead-lettering
});
// Pull and acknowledge
const msg = await req.bext.queue.pull("notifications");
if (msg) {
console.log(msg.payload, msg.attempts);
await req.bext.queue.ack("notifications", msg.id);
}
Real-Time
await req.bext.realtime.publish("orders", { id: 123, status: "shipped" });
Tasks
await req.bext.tasks.register("nightly-cleanup", {
cron: "0 2 * * *",
command: "http://localhost:3000/api/cron/cleanup",
});
const tasks = await req.bext.tasks.list();
await req.bext.tasks.cancel("nightly-cleanup");
TypeScript
The middleware augments Express's Request type globally:
declare global {
namespace Express {
interface Request {
bext: BextClient;
}
}
}
No additional type configuration needed — req.bext is fully typed after importing the middleware.