Skip to content

middleware()

Popii


Popii / middleware

middleware<TState>(mw): PopiiMiddleware<TState>

Defined in: loader/middleware.ts:82

Wraps a middleware function with strict TypeScript types.

Middlewares run before every command and snap handler in the order they are loaded from src/middlewares/ (alphabetically). Use them for auth checks, logging, injecting data into pop.locals, and other cross-cutting concerns.

Regular middleware(pop, next) — must call next() to continue the pipeline. Error middleware(err, pop, next) — only runs when an earlier step throws. Popii detects error middlewares by function arity (function.length === 3). Always declare all three parameters explicitly.

TState = any

PopiiMiddleware<TState>

PopiiMiddleware<TState>

src/middlewares/01-load-user.ts
import { middleware } from "popii";
export default middleware(async (pop, next) => {
const db = (pop.client as any).db;
pop.locals.dbUser = db.query("SELECT * FROM users WHERE id = ?").get(pop.user.id)
?? { id: pop.user.id, balance: 0, premium: false };
await next();
});
import { middleware } from "popii";
export default middleware(async (pop, next) => {
if (process.env.MAINTENANCE === "true") {
await pop.reply({ content: "The bot is under maintenance.", ephemeral: true });
return; // do NOT call next()
}
await next();
});
import { middleware } from "popii";
export default middleware(async (err, pop, next) => {
pop.log.error("Unhandled command error:", err);
await pop.reply({ content: "Something went wrong.", ephemeral: true }).catch(() => {});
});