A production-ready, provider-agnostic email sending toolkit for Next.js, built with TypeScript, Zod, and React Email.
Send email with a clean, template-based API without caring which provider is behind the scenes:
await email.send({
template: "contact",
to: "hello@example.com",
data: { name, email, phone, message },
});Swap resend for SMTP, Nodemailer, SendGrid, or Mailgun later without touching
a single call site.
Status: Phases 1-4 (scaffolding, core email engine, templates, Next.js integration) are complete. The architecture, provider system, template system, a full App Router example, and tests are in place. See Roadmap for what is coming.
- Template-first API — validate, render, and send in one call.
- Provider-agnostic — an
EmailProviderinterface with aResendProviderimplementation. Adding a provider never changes the public API. - Zod validation — the envelope and every template's payload are validated before anything is sent.
- Meaningful errors — typed error classes with stable machine-readable
codes:
EmailValidationError,ProviderError,TemplateError,ConfigurationError. - Startup configuration validation — misconfigured environment variables surface when the client is created, not on the first send.
- Runnable Next.js example — see
examples/nextjs-app-routerfor a contact form, API route, auto-reply, and typed error handling. - React Email templates — two built-in templates (
contact,auto-reply), plus a simple registry for your own. - Plain-text bodies — every send includes a text alternative derived from the rendered HTML (or a per-template override), improving deliverability.
- Preview without sending —
email.preview()renders the exact subject and bodies a send would deliver, ideal for preview servers and snapshot tests. - Strictly typed — strict TypeScript throughout, dual ESM/CJS builds with type declarations.
- Zero provider SDK at import time — the Resend SDK is loaded lazily and declared as an optional peer dependency.
- Node.js >= 20
- pnpm (any recent version)
- React 18 or 19 (peer dependency, for rendering templates)
pnpm add email-toolkit resend react react-domresend is an optional peer dependency: it is only needed when you use the
Resend provider. react / react-dom are required to render React Email
templates.
Create the client from environment variables, which are validated at startup:
EMAIL_PROVIDER=resend
RESEND_API_KEY=re_xxxxxxxx
EMAIL_FROM="Acme <no-reply@acme.com>"
EMAIL_REPLY_TO=support@acme.com| Variable | Required | Description |
|---|---|---|
EMAIL_PROVIDER |
No (default) | Provider name. Currently only resend. |
RESEND_API_KEY |
Yes (resend) | Resend API key. |
EMAIL_FROM |
Yes | Default sender, e.g. "Acme <no-reply@acme.com>". |
EMAIL_REPLY_TO |
No | Default reply-to applied to every send. |
Missing or invalid configuration throws a ConfigurationError listing the
problem variables.
Create the client once, at module scope, so configuration is validated when the app starts:
// lib/email.ts
import { EmailClient } from "email-toolkit";
export const email = EmailClient.fromEnv();Use it in a Route Handler:
// app/api/contact/route.ts
import { NextResponse } from "next/server";
import { EmailValidationError, ProviderError } from "email-toolkit";
import { email } from "@/lib/email";
export async function POST(request: Request) {
const body = await request.json();
try {
const result = await email.send({
template: "contact",
to: "hello@example.com",
data: {
name: body.name,
email: body.email,
phone: body.phone,
message: body.message,
},
});
return NextResponse.json({ ok: true, id: result.id }, { status: 200 });
} catch (error) {
if (error instanceof EmailValidationError) {
return NextResponse.json({ ok: false, error: error.issues }, { status: 400 });
}
if (error instanceof ProviderError) {
console.error("Email provider failed", error);
return NextResponse.json({ ok: false, error: "delivery failed" }, { status: 502 });
}
throw error;
}
}For tests and non-environment setups, construct the client directly:
import { EmailClient, ResendProvider } from "email-toolkit";
const email = new EmailClient({
from: "Acme <no-reply@acme.com>",
replyTo: "support@acme.com",
provider: new ResendProvider({ apiKey: "re_xxxxxxxx" }),
});const result = await email.send({
template: "contact",
to: "hello@example.com",
data: { name: "Jane", email: "jane@example.com", message: "Hi!" },
});
// result: { id: "…", provider: "resend", accepted: ["hello@example.com"], rejected: [] }await email.send({
template: "auto-reply",
to: ["jane@example.com", "john@example.com"],
cc: "team@example.com",
replyTo: "support@example.com",
from: "Acme <hello@acme.com>", // overrides EMAIL_FROM for this send
data: { name: "Jane" },
});const status = await email.healthCheck();
// { ok: true, provider: "resend", latencyMs: 132 }Render the exact subject and bodies a send would deliver, without touching the provider. Ideal for preview servers, documentation, and snapshot tests:
const preview = await email.preview({
template: "contact",
to: "hello@example.com",
data: { name: "Jane", email: "jane@example.com", message: "Hi!" },
});
// { template: "contact", subject: "New contact message from Jane", html: "...", text: "..." }Every send() also includes a plain-text body derived from the rendered HTML
for clients that block HTML.
A template is a Zod schema, a React Email component, and a subject function
bundled into a TemplateDefinition.
// templates/order-confirmation.tsx
import { z } from "zod";
import { Body, Container, Html, Text } from "react-email";
import type { TemplateDefinition } from "email-toolkit";
const schema = z.object({
orderId: z.string().min(1),
customerName: z.string().min(1),
});
function OrderConfirmation({ orderId, customerName }: z.infer<typeof schema>) {
return (
<Html>
<Body>
<Container>
<Text>Thanks {customerName}, your order {orderId} is confirmed.</Text>
</Container>
</Body>
</Html>
);
}
export const orderConfirmationTemplate = {
name: "order-confirmation",
schema,
component: OrderConfirmation,
subject: (data) => `Order ${data.orderId} confirmed`,
} satisfies TemplateDefinition<z.infer<typeof schema>>;Register it and send:
const email = new EmailClient({
from: "Acme <no-reply@acme.com>",
provider: new ResendProvider({ apiKey: "re_xxx" }),
templates: [orderConfirmationTemplate],
});
await email.send({
template: "order-confirmation",
to: "jane@example.com",
data: { orderId: "A-123", customerName: "Jane" },
});You can also register templates on an existing client with
email.registerTemplate(definition). Template data is validated against the
template's Zod schema before rendering, so invalid payloads fail with an
EmailValidationError and are never sent.
Every template automatically ships with a plain-text body derived from its
rendered HTML. If a template needs a hand-crafted text body, add an optional
renderText(data) function to its definition.
Implement the EmailProvider interface and register a factory:
import type { EmailProvider, HealthStatus, SendResult, EmailMessage } from "email-toolkit";
import { ProviderRegistry } from "email-toolkit";
class SmtpProvider implements EmailProvider {
readonly name = "smtp";
async send(message: EmailMessage): Promise<SendResult> {
// send via your SMTP client
return { id: "…", provider: this.name, accepted: [message.to].flat(), rejected: [] };
}
async healthCheck(): Promise<HealthStatus> {
return { ok: true, provider: this.name };
}
}
const registry = new ProviderRegistry();
registry.register({
name: "smtp",
// Declare the env vars this provider needs. They are enforced and mapped
// to config keys automatically by resolveEmailClientOptions().
envMap: { SMTP_HOST: "host", SMTP_PASSWORD: "password" },
create: (config) => new SmtpProvider(config.host as string, config.password as string),
});Providers never see templates or React components; they receive a normalized
EmailMessage (from, to, cc, bcc, replyTo, subject, html, …).
That is what keeps providers trivially replaceable.
Every error extends EmailError and carries a stable code:
| Class | code |
Thrown when |
|---|---|---|
EmailValidationError |
validation |
Envelope or template data fails Zod validation. |
ProviderError |
provider |
A provider rejects or fails to deliver a message. |
TemplateError |
template |
A template name is unknown or duplicates exist. |
ConfigurationError |
configuration |
Environment or provider configuration is invalid. |
try {
await email.send(/* … */);
} catch (error) {
if (error instanceof EmailValidationError) {
console.log(error.issues); // Zod issues with paths and messages
} else if (error instanceof EmailError) {
console.log(error.code, error.message);
}
}Errors also expose cause (the underlying error) and details (structured
context) where relevant. Every error serializes to a stable object via
toJSON(), so JSON.stringify(error) in route handlers or loggers returns a
plain object with name, code, message, and any subtype fields
(issues, missing, provider, templateName):
The sections below summarize the most-used API. For the complete reference, see docs/api.md.
| Method / member | Description |
|---|---|
EmailClient.fromEnv(env?) |
Build from the environment, validating config at startup. |
new EmailClient(options) |
Build programmatically (from, replyTo?, provider, templates?). |
send(options) |
Validate, render, and send through a named template. |
preview(options) |
Render subject/HTML/text without sending (returns TemplatePreview). |
healthCheck() |
Verify the provider is reachable and credentials work. |
registerTemplate(definition) |
Add a template to this client. |
listTemplates() |
Names of registered templates. |
providerName |
Name of the configured provider. |
provider |
The configured provider instance (e.g. for advanced integrations). |
| Field | Type | Description |
|---|---|---|
template |
string |
Registered template name. |
to |
string | string[] |
Recipient(s). |
cc? |
string | string[] |
Carbon copy recipient(s). |
bcc? |
string | string[] |
Blind carbon copy recipient(s). |
replyTo? |
string |
Per-send reply-to override. |
from? |
string |
Per-send from override (may include display name). |
data |
Record<string, unknown> |
Template payload, validated by the template schema. |
- Providers:
ResendProvider,ProviderRegistry,defaultProviderRegistry - Templates:
TemplateRegistry,contactTemplate,autoReplyTemplate,ContactTemplate,AutoReplyTemplate,BUILT_IN_TEMPLATES - Config:
loadEmailEnv,resolveEmailClientOptions,emailEnvSchema - Validation:
sendOptionsSchema,recipientSchema,senderEmailSchema - Utils:
renderTemplate,renderTemplateText,renderMessage,normalizeRecipients
- README — getting started, configuration, usage, examples.
- docs/api.md — complete API reference.
- docs/architecture.md — design, module map, and the send pipeline.
- examples/nextjs-app-router — runnable Next.js App Router integration.
- CHANGELOG.md — release history.
- CONTRIBUTING.md — how to contribute.
pnpm install
pnpm typecheck
pnpm lint
pnpm test
pnpm buildThe package publishes dist/ with ESM (index.js), CommonJS (index.cjs),
and type declarations (index.d.ts / index.d.cts).
ConfigurationError: RESEND_API_KEY is required…— setRESEND_API_KEYor passapiKeytoResendProvider.ConfigurationError: EMAIL_FROM is required— setEMAIL_FROM.ProviderError: Resend rejected the email…— the provider's API returned an error (invalid sender domain, unsupported attachment, etc.). Inspecterror.causeanderror.detailsfor the API response.TemplateError: Unknown template "x"— the template name passed tosendis not registered. ChecklistTemplates().- React is not installed —
reactandreact-domare peer dependencies required to render templates; install them in the consuming app.
Phases 1-4 are complete:
- ✅ Scaffolding, core email engine (EmailProvider, ResendProvider, EmailClient, environment validation, error classes).
- ✅ Template system: React Email,
contactandauto-replytemplates, plain-text bodies, preview, template registration. - ✅ Next.js integration: runnable App Router example with a contact form, API route, and auto-reply.
Next up, without breaking changes to the public API:
- More providers: SMTP, Nodemailer, SendGrid, Mailgun.
- More templates: welcome, password reset, invoice.
- Attachments, scheduling via
scheduledAt, logging, retries with backoff. - Email queueing, analytics, localization, webhooks.
MIT