@smarthivelabs-devs/mailer-sdk-server
v1.2.0
Published
SmartHive Mailer SDK for Node.js backend services
Readme
@smarthivelabs-devs/mailer-sdk-server
Node.js client for the Smart Hive centralized scheduler, mail, and notification platform. Use this in any server-side service (Express, NestJS, Next.js API routes, workers, scripts).
Installation
npm install @smarthivelabs-devs/mailer-sdk-server
# or
pnpm add @smarthivelabs-devs/mailer-sdk-serverRequirements: Node.js ≥ 18 · TypeScript ≥ 5.0
Table of Contents
- Environment Variables
- Quick Start
- Auth Modes
- Scheduler ← start here for new projects
- Notifications
- SMS Sender ID
- App & API Key Management
- Dead Letter Queue
- Error Handling
- Request / Response Hooks
Environment Variables
| Variable | Required | Description |
|---|---|---|
| MAILER_BACKEND_URL | Yes | Base URL of the mailer service |
| MAILER_APP_API_KEY | Yes (app auth) | API key from the Workspace dashboard |
| MAILER_INTERNAL_SECRET | Yes (internal auth) | Shared secret for platform-level calls |
Quick Start
import { createMailerServerClient } from '@smarthivelabs-devs/mailer-sdk-server';
// App-level client — for sending mail, notifications, triggering jobs
const client = createMailerServerClient({
baseUrl: process.env.MAILER_BACKEND_URL!,
auth: {
mode: 'appApiKey',
apiKey: process.env.MAILER_APP_API_KEY!,
},
});
// Send a transactional email
await client.mail.send({
senderEmail: '[email protected]',
senderName: 'Your Company',
recipientEmail: '[email protected]',
subject: 'Welcome aboard',
htmlBody: '<h1>Welcome!</h1><p>Your account is ready.</p>',
textBody: 'Welcome! Your account is ready.',
});
// Send an SMS notification
await client.notifications.send({
channel: 'SMS',
recipient: '+233241234567',
body: 'Your OTP is 847291. Expires in 5 minutes.',
});Auth Modes
There are two auth modes. You will use both in most projects.
App API Key — for day-to-day operations
Use this for sending mail, notifications, and triggering jobs. The key must have the matching service scope enabled (MAIL, NOTIFICATIONS, SCHEDULER, WEBHOOKS). Get this key from the Workspace dashboard → Mailer → your app → API Keys.
const client = createMailerServerClient({
baseUrl: process.env.MAILER_BACKEND_URL!,
auth: {
mode: 'appApiKey',
apiKey: process.env.MAILER_APP_API_KEY!,
},
});Internal Service — for setup and admin operations
Use this for registering schedules, creating apps, and managing projects. Requires the shared internal secret. This client is typically only used in bootstrap/startup code, not on every request.
const internalClient = createMailerServerClient({
baseUrl: process.env.MAILER_BACKEND_URL!,
auth: {
mode: 'internalService',
secret: process.env.MAILER_INTERNAL_SECRET!,
serviceName: 'my-service',
},
});Scheduler
The scheduler lets you run automated jobs on a recurring schedule — daily reports, weekly digests, monthly invoices, health checks, anything. When a schedule fires, the mailer backend calls your own endpoint automatically.
How it works
Your schedule fires (e.g. every day at 8am)
↓
Mailer backend calls your endpoint
↓
POST https://your-backend.com/internal/daily-report
Authorization: Internal <your-secret>You own the logic. The mailer backend is just the clock.
Step 1 — Set up your env variables
MAILER_BACKEND_URL=https://your-mailer-backend.com
MAILER_INTERNAL_SECRET=your-shared-secret
MAILER_APP_ID=your-app-idStep 2 — Create a schedules registration file
Create one file in your project that lists all your schedules. Call it at startup — it is fully idempotent, meaning you can run it on every server restart with no duplicates ever created.
// src/jobs/register-schedules.ts
import { createMailerServerClient } from '@smarthivelabs-devs/mailer-sdk-server';
const mailer = createMailerServerClient({
baseUrl: process.env.MAILER_BACKEND_URL!,
auth: {
mode: 'internalService',
secret: process.env.MAILER_INTERNAL_SECRET!,
serviceName: 'my-project-backend',
},
});
const APP_ID = process.env.MAILER_APP_ID!;
const BASE_URL = process.env.APP_URL!; // your own backend's public URL
export async function registerSchedules() {
await Promise.all([
// Daily report at 8am Lagos time
mailer.schedules.registerHttpJob({
appId: APP_ID,
name: 'Daily Report — 8am',
type: 'CRON',
cronExpression: '0 8 * * *',
timezone: 'Africa/Lagos',
url: `${BASE_URL}/internal/daily-report`,
}),
// Weekly digest every Monday at 9am
mailer.schedules.registerHttpJob({
appId: APP_ID,
name: 'Weekly Digest — Monday 9am',
type: 'CRON',
cronExpression: '0 9 * * MON',
timezone: 'Africa/Lagos',
url: `${BASE_URL}/internal/weekly-digest`,
}),
// Monthly invoice run on the 1st at midnight
mailer.schedules.registerHttpJob({
appId: APP_ID,
name: 'Monthly Invoice Run',
type: 'CRON',
cronExpression: '0 0 1 * *',
timezone: 'UTC',
url: `${BASE_URL}/internal/invoices/generate`,
}),
]);
console.log('[schedules] registered');
}One schedule per unique name. The name is the idempotency key. If a schedule with that name already exists for this app,
registerHttpJobreturns it as-is and creates nothing. Rename it only if you want to replace it with a new one.
Step 3 — Call it at startup
// src/main.ts (Express / NestJS / any Node.js app)
import { registerSchedules } from './jobs/register-schedules';
async function bootstrap() {
// ... your app setup
await registerSchedules(); // safe to run on every restart
app.listen(3000);
}
bootstrap();For NestJS, put it in onApplicationBootstrap:
// src/app.module.ts or a dedicated SchedulesModule
import { Injectable, OnApplicationBootstrap } from '@nestjs/common';
import { registerSchedules } from './jobs/register-schedules';
@Injectable()
export class SchedulesBootstrap implements OnApplicationBootstrap {
async onApplicationBootstrap() {
await registerSchedules();
}
}Step 4 — Create the endpoint in your own backend
This is the code that runs when the schedule fires. It lives in your project, not in the mailer backend.
// Express example
app.post('/internal/daily-report', verifyInternalSecret, async (req, res) => {
// your logic here — query DB, send emails, generate reports, whatever
await generateDailyReport();
res.json({ ok: true });
});
// NestJS example
@Post('internal/daily-report')
@UseGuards(InternalSecretGuard)
async dailyReport() {
await this.reportService.generateDaily();
return { ok: true };
}Verify the incoming secret so only the mailer backend can trigger it:
// Express middleware
function verifyInternalSecret(req, res, next) {
const auth = req.headers['authorization'] ?? '';
const secret = auth.replace('Internal ', '');
if (secret !== process.env.MAILER_INTERNAL_SECRET) {
return res.status(401).json({ message: 'Unauthorized' });
}
next();
}registerHttpJob — full options
await mailer.schedules.registerHttpJob({
appId: string; // your app id
name: string; // unique name — used as the idempotency key
type: ScheduleType; // see types below
url: string; // your endpoint URL
method?: string; // default: 'POST'
body?: object; // optional JSON body sent to your endpoint
timezone?: string; // e.g. 'Africa/Lagos', 'UTC' — default: 'UTC'
cronExpression?: string // required when type is 'CRON'
intervalSeconds?: number // required when type is 'INTERVAL'
runAt?: Date | string; // required for 'ONE_TIME' / 'DELAYED'
enabled?: boolean; // default: true
});Schedule types:
| Type | When it runs |
|---|---|
| CRON | Custom cron expression — most flexible |
| DAILY | Once every day |
| WEEKLY | Once every week |
| MONTHLY | Once every month |
| INTERVAL | Every N seconds |
| ONE_TIME | Once at a specific time, then done |
| DELAYED | Like ONE_TIME but relative delay |
| RRULE | RFC 5545 recurrence rule |
Cron expression cheatsheet:
| Expression | Meaning |
|---|---|
| 0 8 * * * | Every day at 8am |
| 0 9 * * MON | Every Monday at 9am |
| 0 0 1 * * | 1st of every month at midnight |
| 0 9 * * MON-FRI | Weekdays at 9am |
| */30 * * * * | Every 30 minutes |
Managing existing schedules
// List all schedules for an app
const { data } = await mailer.schedules.list({ appId: APP_ID });
// Pause a schedule (stops it from firing without deleting it)
await mailer.schedules.pause('schedule_id');
// Resume a paused schedule
await mailer.schedules.resume('schedule_id');
// Update a schedule (e.g. change the cron expression)
await mailer.schedules.update('schedule_id', {
cronExpression: '0 9 * * MON-FRI',
});Trigger a job immediately (one-shot, outside of a schedule)
const job = await client.jobs.create({
jobDefinitionId: 'def_abc123',
payload: { userId: 'user_xyz' },
});
const status = await client.jobs.getRuntimeJob(job.id);
// status.status → 'QUEUED' | 'RUNNING' | 'SUCCEEDED' | 'FAILED'Complete new project setup (end-to-end)
If the app hasn't been provisioned yet via the dashboard, you can do it all from code:
// 1. Provision the app once (or do this from the Workspace dashboard)
const { app } = await internalClient.projects.provisionMailerApp('workspace-project-id', {
name: 'My New Project',
slug: 'my-new-project',
environment: 'production',
schedulerEnabled: true,
});
// Store app.id as MAILER_APP_ID in your env
// 2. Register schedules at startup — that's it
await registerSchedules();Send a transactional email
await client.mail.send({
senderEmail: '[email protected]',
senderName: 'Smart Hive',
recipientEmail: '[email protected]',
recipientName: 'Jane Doe',
subject: 'Welcome to Smart Hive',
htmlBody: '<h1>Welcome!</h1>',
textBody: 'Welcome!',
priority: 1,
maxAttempts: 3,
});Send with a saved template
await client.mail.send({
senderEmail: '[email protected]',
recipientEmail: '[email protected]',
templateKey: 'welcome-email',
variables: {
firstName: 'Jane',
activationUrl: 'https://app.smarthive.co/activate?token=abc',
},
});Send with attachments
import { readFileSync } from 'fs';
await client.mail.send({
senderEmail: '[email protected]',
recipientEmail: '[email protected]',
subject: 'Invoice #INV-2024-001',
htmlBody: '<p>Please find your invoice attached.</p>',
attachments: [
{
filename: 'invoice.pdf',
contentBase64: readFileSync('./invoice.pdf').toString('base64'),
contentType: 'application/pdf',
},
],
});Inline SMTP (bypass the queue, send immediately)
await client.mail.send({
senderEmail: '[email protected]',
recipientEmail: '[email protected]',
subject: 'CRITICAL: payment gateway down',
htmlBody: '<p>Investigate immediately.</p>',
inlineSmtp: {
host: 'smtp.sendgrid.net',
port: 587,
secure: false,
username: 'apikey',
password: process.env.SENDGRID_API_KEY!,
},
});Bulk mail
await client.mail.bulkSend({
batchName: 'april-newsletter',
messages: [
{
senderEmail: '[email protected]',
recipientEmail: '[email protected]',
templateKey: 'monthly-newsletter',
variables: { firstName: 'Alice', edition: 'April 2024' },
},
{
senderEmail: '[email protected]',
recipientEmail: '[email protected]',
templateKey: 'monthly-newsletter',
variables: { firstName: 'Bob', edition: 'April 2024' },
},
],
});Notifications
// SMS — uses project-level smsSenderId by default (set via integrationConfig.upsert)
await client.notifications.send({ channel: 'SMS', recipient: '+233241234567', body: 'Your OTP is 847291.' });
// SMS — per-message sender override (title takes priority over smsSenderId)
await client.notifications.send({ channel: 'SMS', recipient: '+233241234567', body: 'Your OTP is 847291.', title: 'MyBrand' });
// Expo Push
await client.notifications.send({
channel: 'PUSH',
recipient: 'ExponentPushToken[xxxxxx]',
title: 'New message',
body: 'You have a new message from Jane.',
data: { screen: 'inbox' },
});
// In-App (stored in DB, queried by client)
await client.notifications.send({
channel: 'IN_APP',
recipient: 'user_uuid_here',
title: 'Task assigned',
body: 'You have been assigned to Project Alpha.',
data: { projectId: 'proj_xyz' },
});
// Webhook dispatch
await client.notifications.dispatchWebhook({
channel: 'WEBHOOK',
webhookEndpointId: 'wh_endpoint_abc123',
body: JSON.stringify({ event: 'order.completed', orderId: 'ord_789' }),
data: { event: 'order.completed' },
});SMS Sender ID
Configure a project-level SMS sender name so every outbound SMS from an app uses it by default. The sender must be pre-approved on your Arkesel account.
Resolution order: per-message title → app smsSenderId → 'SmartHive'
await internalClient.integrationConfig.upsert('app_abc123', {
mode: 'PAYLOAD',
allowedServices: ['NOTIFICATIONS'],
smsSenderId: 'MyBrand',
});App & API Key Management
// List API keys for an app
const keys = await client.apps.listApiKeys('app_id');
// Create an API key
const apiKey = await client.apps.createApiKey('app_id', {
name: 'Production Key',
allowedServices: ['MAIL', 'NOTIFICATIONS', 'SCHEDULER'],
});
// apiKey.plaintextKey — shown once, store it securely
// Update which services a key can access
await client.apps.updateApiKeyServices('app_id', 'key_id', {
allowedServices: ['MAIL', 'NOTIFICATIONS'],
});
// Revoke a key
await client.apps.revokeApiKey('app_id', 'key_id');Dead Letter Queue
const deadMail = await client.deadLetter.listMail();
console.log(deadMail[0].failureReason);
await client.deadLetter.requeueMail('dead_letter_id');
const deadJobs = await client.deadLetter.listRuntimeJobs();
await client.deadLetter.requeueRuntimeJob('dead_letter_id');Error Handling
import { MailerApiError } from '@smarthivelabs-devs/mailer-sdk-server';
try {
await client.mail.send({ ... });
} catch (err) {
if (err instanceof MailerApiError) {
console.error(err.statusCode, err.message, err.body);
}
}Common errors
| Status | Cause | Fix |
|---|---|---|
| 401 | Missing or invalid API key | Check MAILER_APP_API_KEY |
| 403 | Key exists but missing service scope | Add MAIL / SCHEDULER etc. in the Workspace dashboard → Mailer → Apps → API Keys |
| 422 | Invalid request body | Check required fields |
| 429 | Rate limit exceeded | Reduce rate or update rate limit profile |
| 502 | Mailer backend unreachable | Check MAILER_BACKEND_URL |
Request / Response Hooks
const client = createMailerServerClient({
baseUrl: process.env.MAILER_BACKEND_URL!,
auth: { mode: 'appApiKey', apiKey: process.env.MAILER_APP_API_KEY! },
hooks: {
onRequest: (req) => console.log(`[mailer] ${req.method} ${req.url}`),
onResponse: (res) => { if (!res.ok) console.warn(`[mailer] ${res.status} ${res.url}`); },
},
});Exports
createMailerServerClient(options)— main factoryMailerServerClient— client typeMailerServerClientOptions— options typeMailerApiError— error class (statusCode,message,body)AppApiKeyAuth,InternalServiceAuth— auth mode types
All types (inputs, records, enums) are included in this package — no additional install needed.
