Implement Multi-Tenant / Multi-Account Isolation
mainEvery WeChatBot instance is fully isolated (own HTTP client, events, and message poller). To run multiple accounts side-by-side without global state conflicts, ensure each instance has its own storage namespace or storageDir.
When using the Node.js SDK, you can pass a custom storage implementation and use login callbacks to handle QR codes (e.g., pushing them to a specific user's web UI).
Critical Requirements for Multi-Tenancy:
- Storage Isolation: Each account must have its own
storageDiror storage namespace to prevent credential overwriting. - Instance Uniqueness: Only one live instance (poller) should run per account to avoid cursor overwrites. Use advisory locks in multi-machine deployments.
- Session Persistence: Credentials are saved to disk/storage, so
login()will automatically restore sessions after a restart.
// One instance per tenant, credentials isolated per tenant
const bot = new WeChatBot({
storage: new PostgresStorage(pool, tenantId), // or { storageDir: `/data/${tenantId}` }
})
await bot.login({
callbacks: {
onQrUrl: (url) => pushQrToWebUI(tenantId, url),
onScanned: () => notify(tenantId, 'Scanned — waiting for confirmation'),
onExpired: () => refreshQr(tenantId),
},
})
await bot.start()