npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@contentgrowth/content-emailing

v0.7.2

Published

Unified email delivery and template management system with UI components

Readme

@emails/backend

A comprehensive email management and delivery package designed for Cloudflare Workers.

This package provides a complete solution for handling transactional emails, managing templates (with Markdown and variable substitution), and tracking email events (opens, clicks). It relies on Cloudflare D1 for storage and supports optional Durable Objects for high-performance caching.

Features

  • Multi-Provider Support: Switch between MailChannels, SendGrid, Resend, SendPulse, or Mock (for testing) via configuration.
  • Template Management: Create and edit email templates using Markdown.
  • Dynamic Variables: Mustache-style variable substitution ({{ user_name }}) in subjects and bodies.
  • Email Tracking: Built-in support for tracking email opens (pixel) and link clicks.
  • Cloudflare D1: Stores templates, settings, and logs in D1 SQL database.
  • Durable Objects Cache: Optional caching layer for high-speed template retrieval.
  • React Components: Ready-to-use UI components for managing templates (TemplateManager, TemplateEditor).

Requirements

  • Runtime: Cloudflare Workers (or compatible environment like Hono on Node.js with D1 bindings).
  • Framework: built with Hono.
  • Database: Cloudflare D1.

Installation

npm install @emails/backend

Setup & Usage

1. Initialize Email Service

In your worker or Hono app:

import { EmailService } from '@emails/backend';

// Initialize with your environment (needs DB binding)
// Auto-detects 'EMAIL_TEMPLATE_CACHE' Durable Object if present!
const emailService = new EmailService(env, {
  // Optional: Rename tables if needed
  emailTablePrefix: 'system_email_', // default (for templates/logs)
  // emailSettingsTable: 'system_settings', // default (for settings)
  // emailSettingsKeyPrefix: 'email_', // Optional: filter settings in shared table

  defaults: {
    fromName: 'My App',
    fromAddress: '[email protected]',
    provider: 'resend' // or 'mailchannels', 'sendgrid', 'mock'
  },
  // API keys from env
  resend_api_key: env.RESEND_API_KEY
});

2.- EmailingCacheDO.js - Durable Object for caching templates & settings, you can enable the read-through cache using Cloudflare Durable Objects.

The "Magic" Way (Auto-detection):

  1. Add a Durable Object binding named EMAIL_TEMPLATE_CACHE to your wrangler.toml.
  2. Point it to the EmailingCacheDO class from this package.
  3. Initialize EmailService(env) normally. It will automatically find and use the cache.

wrangler.toml:

[[durable_objects.bindings]]
name = "EMAIL_TEMPLATE_CACHE"
class_name = "EmailTemplateCacheDO"

[[migrations]]
tag = "v1"
new_classes = ["EmailTemplateCacheDO"]

The Explicit Way: If you use a custom binding name or cache implementation:

import { EmailService, createDOCacheProvider } from '@emails/backend';

const cache = createDOCacheProvider(env.MY_CUSTOM_BINDING);
const service = new EmailService(env, config, cache);

Custom Cache Provider Interface: You can also implement your own cache provider (e.g., using Redis/KV). It must match this interface:

const myCustomCache = {
  // Return template object or null
  async getTemplate(templateId) {
    // implementation
  },

  // Called when template is saved/updated
  async putTemplate(template) {
    // implementation (usually just invalidates cache)
  },

  // Called when template is deleted
  async deleteTemplate(templateId) {
    // implementation
  }
};

const service = new EmailService(env, config, myCustomCache);

const service = new EmailService(env, config, myCustomCache);


### 3. Settings Management (Hybrid Caching)

The package supports a robust caching strategy for email settings (provider API keys, SMTP config, etc.).

**Case A: Default System Settings (Zero Config)**
If you store settings in the `system_settings` table (default schema), the Durable Object handles everything automatically:
1. `EmailService` asks DO for settings.
2. If not cached, **DO queries D1 directly** (Read-Through).
3. If cached, returns instantly.

**Case B: Component/Tenant Settings (Custom Logic)**
If you need to load settings from a custom source (e.g., tenant tables, KV, external API), simple provide loader/updater callbacks:

```javascript
const emailService = new EmailService(env, {
  // Custom Loader (Read-Aside)
  // The service will load this, THEN cache it in the DO for you.
  settingsLoader: async (profile, tenantId) => {
    return await env.TENANT_DB.prepare('SELECT * FROM tenant_config WHERE id = ?').bind(tenantId).first();
  },

  // Custom Updater (Write-Aside)
  // required if you use saveSettings()
  settingsUpdater: async (profile, tenantId, settings) => {
    await env.TENANT_DB.prepare('UPDATE tenant_config SET ...').run();
  }
});

4. Database Schema

Ensure your D1 database has the required tables. See examples/mocks/MockD1.js for the schema structure, or refer to the provided SQL migration files (if available).

Tables needed:

  • system_email_templates
  • system_settings
  • system_email_sends (for logs)

5. Add API Routes

Mount the management routes in your Hono app:

import { createTemplateRoutes, createTrackingRoutes } from '@emails/backend';

// Template management (protected routes recommended)
app.route('/api/templates', createTemplateRoutes(emailService));

// Public tracking routes (opens/clicks)
app.route('/email', createTrackingRoutes(emailService));

Running the Example

A fully functional example server is included in examples/. It uses a Mock D1 implementation so you can run it locally without deploying to Cloudflare.

cd examples
npm install
npm start

Visit http://localhost:3456/portal/ to try the Template Manager UI.

Environment Variables

Configure your provider using standard environment variables or pass them in the config object:

  • EMAIL_PROVIDER: resend, sendgrid, mailchannels, sendpulse, or mock
  • RESEND_API_KEY
  • SENDGRID_API_KEY
  • SENDPULSE_CLIENT_ID / SENDPULSE_CLIENT_SECRET

Architecture Note

This package is "Cloudflare-native". It expects env.DB to be a D1 binding. If running outside Cloudflare (e.g. Node.js), you must provide a D1-compatible mock or adapter, as demonstrated in the examples/ folder.