Integration Recipes

Code Examples & Recipes

Ready-to-use boilerplate patterns and implementation examples for integrating MBKAuthe into your Node.js apps.

1. Minimal Express Application Setup

Initialize Express, mount MBKAuthe, and protect public and private routes.

server.js
import express from "express";
import dotenv from "dotenv";
import mbkauthe, { sessVal, roleChk } from "mbkauthe";

dotenv.config();

const app = express();
app.use(express.json());

// Mount MBKAuthe core router
app.use(mbkauthe);

// Public route
app.get("/", (req, res) => res.send("Home Page"));

// Protected dashboard
app.get("/dashboard", sessVal, (req, res) => {
  res.send(`Hello ${req.session.user.username}!`);
});

// Superadmin role check
app.get("/admin", sessVal, roleChk("superadmin"), (req, res) => {
  res.send("Superadmin Area");
});

app.listen(3000, () => console.log("Server running at :3000"));

2. Dual-Database Repository with Transactions

Extend BaseRepository for seamless PostgreSQL and SQLite support.

UserRepository.js
import { BaseRepository, defaultAdapter } from "mbkauthe";

export class UserRepository extends BaseRepository {
  constructor(adapter = defaultAdapter) {
    super(adapter);
  }

  async findByUsername(username) {
    const { rows } = await this.query(
      "SELECT id, username, email, role FROM users WHERE username = $1",
      [username]
    );
    return rows[0] || null;
  }

  async transferCredits(fromUserId, toUserId, amount) {
    return await this.withTransaction(async (txRepo) => {
      await txRepo.query("UPDATE accounts SET credits = credits - $1 WHERE user_id = $2", [amount, fromUserId]);
      await txRepo.query("UPDATE accounts SET credits = credits + $1 WHERE user_id = $2", [amount, toUserId]);
    });
  }
}

3. Server-to-Server Webhook Protection

Protect internal microservice endpoints using authenticate(token).

webhooks.js
import { authenticate } from "mbkauthe";

// Requires Authorization: Bearer <MAIN_SECRET_TOKEN>
app.post(
  "/api/internal/deploy-trigger",
  authenticate(process.env.MAIN_SECRET_TOKEN),
  (req, res) => {
    res.json({ success: true, message: "Deploy initiated" });
  }
);