Convex
Send email from Convex — scheduled from the mutation that writes the record, so it goes only if the write commits; an action with an idempotency key and retries; webhooks into an HTTP action; and sign-in codes with Better Auth on Convex.
@charchy/send runs in Convex's default runtime: it needs only fetch and
Web Crypto. No "use node".
1. Install and set the key
npm install @charchy/sendnpx convex env set CHARCHY_SEND_KEY chy_test_…
npx convex env set CHARCHY_SEND_FROM "My App <no-reply@myapp.com>"
npx convex env set CHARCHY_WEBHOOK_SECRET whsec_…Each deployment has its own variables: set a live key (chy_live_…) on
production with --prod, or in the dashboard under Settings → Environment
Variables.
2. Send only if the write commits
Mutations can't call fetch, and they are transactional. So the mutation that
saves the record schedules the send: runAfter from a mutation is part of
the transaction — if the mutation fails, nothing is scheduled.
import { defineSchema, defineTable } from "convex/server"
import { v } from "convex/values"
export default defineSchema({
orders: defineTable({
email: v.string(),
total: v.number(),
receiptEmailId: v.optional(v.string()), // "em_…", once Charchy Send accepted it
receiptStatus: v.optional(v.string()), // "delivered", "bounced", … from webhooks
receiptStatusAt: v.optional(v.number()),
}),
})import { v } from "convex/values"
import { internal } from "./_generated/api"
import { internalMutation, internalQuery, mutation } from "./_generated/server"
export const place = mutation({
args: { email: v.string(), total: v.number() },
handler: async (ctx, args) => {
const orderId = await ctx.db.insert("orders", args)
// Scheduled only if this mutation commits: no receipt for an order that was never saved.
await ctx.scheduler.runAfter(0, internal.emails.sendReceipt, { orderId })
return orderId
},
})
export const get = internalQuery({
args: { orderId: v.id("orders") },
handler: (ctx, { orderId }) => ctx.db.get(orderId),
})
export const saveReceiptEmailId = internalMutation({
args: { orderId: v.id("orders"), emailId: v.string() },
handler: (ctx, { orderId, emailId }) => ctx.db.patch(orderId, { receiptEmailId: emailId }),
})3. The action that sends
import { CharchySend, type CharchySendError } from "@charchy/send"
import { v } from "convex/values"
import { internal } from "./_generated/api"
import { internalAction } from "./_generated/server"
/** Reads CHARCHY_SEND_KEY when an email is sent, so pushing never needs the key. */
const send = new CharchySend()
const MAX_ATTEMPTS = 5
export const sendReceipt = internalAction({
args: { orderId: v.id("orders"), attempt: v.optional(v.number()) },
handler: async (ctx, { orderId, attempt = 1 }) => {
const order = await ctx.runQuery(internal.orders.get, { orderId })
if (!order || order.receiptEmailId) return // gone, or already sent
const { data, error } = await send.emails.send(
{
from: process.env.CHARCHY_SEND_FROM!,
to: order.email,
subject: "Your receipt",
html: `<p>Thanks! You paid ${order.total.toFixed(2)} USD.</p>`,
tags: { type: "receipt", order_id: orderId },
},
// From the document: every retry, the SDK's or ours, is the same email.
{ idempotencyKey: `receipt/${orderId}` }
)
if (error) {
if (isWorthRetrying(error) && attempt < MAX_ATTEMPTS) {
const delayMs = (error.retryAfterSeconds ?? 60 * 2 ** attempt) * 1000
await ctx.scheduler.runAfter(delayMs, internal.emails.sendReceipt, { orderId, attempt: attempt + 1 })
return
}
throw error // in the Convex logs, with error.code, error.docs and error.requestId
}
await ctx.runMutation(internal.orders.saveReceiptEmailId, { orderId, emailId: data.id })
},
})
/** An outage or a busy moment. A refusal (402, 403, 422…) won't change on a retry. */
function isWorthRetrying(error: CharchySendError): boolean {
return (
error.code === "network_error" ||
error.code === "rate_limit_exceeded" ||
error.code === "daily_limit_reached" ||
error.code === "idempotency_in_flight" ||
(error.statusCode !== null && error.statusCode >= 500)
)
}- One client at the top of the file. Creating it reads no key — the key
is read when an email is sent — so pushing works on a deployment without
CHARCHY_SEND_KEY; a send there returnsmissing_api_keyand nothing goes out. - Retries. Convex runs a scheduled action at most once and never retries
it. The SDK already retries quick failures (2 more tries within the call);
for a longer outage the action schedules itself again — 2, 4, 8, 16
minutes, or the API's
Retry-After. The idempotency key comes from the order id, so a retry can never send a second receipt: within 24 hours the API answers it with the first email's id. For many emails, the Workpool or Action Retrier components do the same with backoff and limits. - The
em_…id goes back on the document through an internal mutation;order.receiptEmailIdalso stops a second run before it calls the API. - The
order_idtag comes back on every webhook event for this email.
4. Webhooks into an HTTP action
import { verifyWebhook, WebhookVerificationError } from "@charchy/send"
import { httpRouter } from "convex/server"
import { internal } from "./_generated/api"
import { httpAction } from "./_generated/server"
const http = httpRouter()
const RECEIPT_STATUSES = {
"email.delivered": "delivered",
"email.bounced": "bounced",
"email.complained": "complained",
} as const
http.route({
path: "/webhooks/charchy",
method: "POST",
handler: httpAction(async (ctx, request) => {
let event
try {
// The raw body; the secret defaults to CHARCHY_WEBHOOK_SECRET.
event = await verifyWebhook({ payload: await request.text(), headers: request.headers })
} catch (error) {
if (error instanceof WebhookVerificationError) return new Response("Invalid signature", { status: 400 })
throw error
}
if (event.type === "email.delivered" || event.type === "email.bounced" || event.type === "email.complained") {
const orderId = event.data.tags.order_id // the tag sendReceipt set
if (orderId) {
await ctx.runMutation(internal.orders.recordReceiptStatus, {
orderId,
status: RECEIPT_STATUSES[event.type],
at: Date.parse(event.createdAt),
})
}
}
return new Response(null, { status: 204 })
}),
})
export default httpThe mutation it calls, next to the others in convex/orders.ts:
export const recordReceiptStatus = internalMutation({
args: { orderId: v.string(), status: v.string(), at: v.number() },
handler: async (ctx, { orderId, status, at }) => {
const id = ctx.db.normalizeId("orders", orderId)
const order = id && (await ctx.db.get(id))
// Events can arrive twice and out of order: never let an older one win.
if (!order || (order.receiptStatusAt ?? 0) > at) return
await ctx.db.patch(order._id, { receiptStatus: status, receiptStatusAt: at })
},
})In the Charchy dashboard, under Webhooks, add your deployment's HTTP
actions URL — it ends in .convex.site, not .convex.cloud — plus the path:
https://<deployment>.convex.site/webhooks/charchy.
A thrown error answers 500, and the event is sent again; the mutation
ignores a repeat. Shorter, when every handler is quick:
import { webhookHandler } from "@charchy/send"
http.route({
path: "/webhooks/charchy",
method: "POST",
handler: httpAction((ctx, request) =>
webhookHandler({
"email.bounced": (event) =>
ctx.runMutation(internal.orders.recordReceiptStatus, {
orderId: event.data.tags.order_id ?? "",
status: "bounced",
at: Date.parse(event.createdAt),
}),
})(request)
),
})5. Sign-in codes with Better Auth on Convex
With @convex-dev/better-auth (set up
as in its guide for your framework), the emailOTP callback schedules the
send instead of waiting for it:
import { createClient, type GenericCtx } from "@convex-dev/better-auth"
import { convex } from "@convex-dev/better-auth/plugins"
import { requireRunMutationCtx } from "@convex-dev/better-auth/utils"
import { betterAuth } from "better-auth/minimal"
import { emailOTP } from "better-auth/plugins"
import { components, internal } from "./_generated/api"
import type { DataModel } from "./_generated/dataModel"
import authConfig from "./auth.config"
const CODE_LIFETIME_SECONDS = 5 * 60
export const authComponent = createClient<DataModel>(components.betterAuth)
export const createAuth = (ctx: GenericCtx<DataModel>) =>
betterAuth({
baseURL: process.env.SITE_URL,
database: authComponent.adapter(ctx),
plugins: [
emailOTP({
expiresIn: CODE_LIFETIME_SECONDS,
async sendVerificationOTP({ email, otp, type }) {
// Scheduled, not awaited: the request doesn't wait on the email
// (Better Auth's advice against timing attacks), and the send runs
// in an action of its own.
await requireRunMutationCtx(ctx).scheduler.runAfter(0, internal.emails.sendSignInCode, {
email,
otp,
type,
expiresAt: Date.now() + CODE_LIFETIME_SECONDS * 1000,
})
},
}),
convex({ authConfig }),
],
})The action, next to sendReceipt:
export const sendSignInCode = internalAction({
args: { email: v.string(), otp: v.string(), type: v.string(), expiresAt: v.number() },
handler: async (ctx, { email, otp, type, expiresAt }) => {
const { error } = await send.emails.send(
{
from: process.env.CHARCHY_SEND_FROM!,
to: email,
subject: `Your code: ${otp}`,
text: `Your code is ${otp}. It expires in 5 minutes.`,
expiresAt: new Date(expiresAt), // dropped and refunded if it can't leave in time
tags: { type: type.replaceAll("-", "_") },
},
{ idempotencyKey: `otp/${type}/${email}/${otp}` }
)
if (error) throw error
},
})The auth routes run as HTTP actions, and server-side auth.api calls from a
mutation carry a scheduler too; requireRunMutationCtx throws if a query ever
reaches the callback. The same pattern fits sendResetPassword,
sendVerificationEmail and magicLink's sendMagicLink — see
Better Auth for their options.
6. Try it
npx convex run orders:place '{"email": "delivered@sim.charchy.krd", "total": 12.5}'The receipt shows on the Charchy dashboard's Emails page; a moment later
the email.delivered webhook sets receiptStatus on the order. Use
bounced@sim.charchy.krd for the bounce path —
magic addresses.