@spacetimedb/resend
v0.1.0
Published
Resend email delivery, webhook verification, and event storage for SpacetimeDB TypeScript modules.
Readme
@spacetimedb/resend
Send email from your SpacetimeDB application through Resend. Use it for welcome messages, receipts, and notifications, then track whether each message was delivered, delayed, or bounced.
The submodule stores delivery status in your database and updates it from Resend webhooks. Your application decides who can send email and see its history.
Install
Run this in your SpacetimeDB TypeScript module directory:
npm install @spacetimedb/resendRequires SpacetimeDB SDK, CLI, and server 2.12 or later.
Integrate into an application
Add Resend to your module and initialize it:
import { schema } from 'spacetimedb/server';
import * as resend from '@spacetimedb/resend/submodule';
const spacetimedb = schema({ resend });
export default spacetimedb;
export const init = spacetimedb.init(ctx => {
resend.install(ctx.as.resend);
});After publishing, configure your Resend API key, sender address, and webhook
signing secret as the database owner or a Resend administrator. When mounted
as resend, use resend.set_resend_config; the arguments are shown in
Standalone configuration.
Call resend.sendEmailRequest from a procedure that checks who may send email
and which recipients they may contact. Apply rate limits before sending:
resend.sendEmailRequest(ctx.as.resend, {
to: ['[email protected]'],
subject: 'Welcome',
html: '<p>Hello.</p>',
tagsJson: JSON.stringify([
{ name: 'userId', value: 'u_123' },
{ name: 'orgId', value: 'launch' },
]),
});For delivery updates, register makeResendWebhookHandler() on an HTTP route
and add that URL in Resend. See the Dispatch example for a
complete send procedure, webhook route, and views that show each user only
their own email history.
Standalone configuration
When running Resend as its own database, configure it with the unprefixed operation below. Credentials are private, and the publishing owner is the first administrator.
spacetime call --server http://127.0.0.1:3000 spacetime-resend set_resend_config \
'"re_..."' \
'{"some":"whsec_..."}' \
'{"some":"[email protected]"}'Args: apiKey, webhookSigningSecret (required for webhook ingest), defaultFrom (optional).
For t.option(...) CLI arguments, use null for no value and
{"some":"value"} for a string value.
Verify:
spacetime call --server http://127.0.0.1:3000 spacetime-resend get_resend_config_status '{}'Private tables
| Table | Key | Notes |
| ----------------------- | ----------- | ------------------------------------------------------------ |
| resend_email | resend_id | one row per outbound email; status reflects latest webhook |
| resend_delivery_event | event_id | append-only audit log of every event for an email |
resend_webhook_event- idempotency logresend_config- credentials singletonresend_admin_identity- admin allowlist
None of the Resend base tables are subscribable. Email recipients, subject,
body, tracking state, webhook payloads, and signature headers remain private.
Host modules should expose caller- or tenant-scoped views over userId or
orgId; the included example demonstrates this pattern.
API
Setup
set_resend_config(apiKey, webhookSigningSecret, defaultFrom)get_resend_config_status()-{ isConfigured, hasWebhookSecret, apiKeyLength, ... }add_admin_identity(identity)/remove_admin_identity(identity)
Outbound
send_email({ from, to, subject, html, text, cc, bcc, replyTo, tagsJson, headersJson, scheduledAt, idempotencyKey})- admin-gated; inserts aresend_emailrow withstatus = queued, returns{ resendId }. The first webhook flips it tosent/delivered.cancel_email({ resendId })- admin-gatedresend_api_request({ method, path, jsonBody, idempotencyKey })- admin-gated request to a relativeapi.resend.compath; accepted methods areGET,POST,PATCH, andDELETE
Email sends accept up to 100 combined to, cc, and bcc recipients. Address
fields are capped at 320 characters, subjects at 998 characters, HTML and text
at 200,000 characters each, and tag or header JSON at 16 KiB. Control characters
in address, subject, and schedule fields are rejected before provider HTTP.
The generated client calls your application's send procedure, such as the
sendDispatch procedure in the example:
const result = await conn.procedures.sendDispatch({
to: '[email protected]',
subject: 'Welcome',
message: 'Your workspace is ready.',
});
if (!result.ok) throw new Error(result.message);Subscribe to a caller-scoped host view for delivery status. Keep the private Resend tables and generic administrative send operation restricted to operators.
Webhook ingest / replay
ingest_resend_webhook(eventId, eventType, payloadJson, signatureHeader, timestampHeader)- deduplicates events by thesvix-idheader passed aseventIdreplay_webhook_event(eventId)- re-applies a stored eventmakeResendWebhookHandler()builds a direct HTTP webhook handler for a host router.
The HTTP handler returns 200 after applying an event, for an already processed
event, and for signed event types the submodule does not handle, which are stored
as Ignored. Invalid payloads return 400 and retain a failed event record;
redelivery retries failed records. Unexpected transaction failures propagate to
the HTTP runtime.
The reducer throws, writing nothing, when metadata, size, headers, secret, or
signature checks reject a request. Once a signed event is stored, the reducer
commits: an invalid payload keeps its Failed event record with the error
message. Callers read the outcome with get_webhook_event.
Delivery timestamps use the provider's event time. Older events cannot replace newer status, and an earlier delivery stage cannot replace a later one. Queued send responses preserve any webhook state already recorded. Opens, clicks, and complaints update their own fields without changing delivery status. Error, bounce, and failure details change only when their event sets the status.
Admin queries
get_email,list_emails_by_user_id,list_emails_by_org_id,list_emails_by_statuslist_delivery_events_for_emailget_webhook_event- stored event withstatus(Received,Processed,Ignored, orFailed) anderrorMessage
List procedures return at most 1,000 rows. Host applications should expose caller-scoped, paginated views for product-facing history.
Errors
errors from @spacetimedb/resend/submodule lists the resend.* codes the
submodule throws.
Package entrypoints:
@spacetimedb/resendcan run as a standalone email database.@spacetimedb/resend/submodulesupplies submodule configuration, delivery, webhook, and query helpers.
Webhook events handled
email.sent email.delivered
email.delivery_delayed email.bounced
email.complained email.failed
email.opened email.clickedOther signed event types, such as email.received, contact.*, and domain.*,
are acknowledged and stored as Ignored.
opened / clicked / complained are recorded as flags + timestamps and leave status unchanged. Terminal states (delivered, bounced, failed, cancelled) and in-flight states (queued, sent, delivery_delayed) live in the status column.
Webhook signature verification
The ingest_resend_webhook reducer and the makeResendWebhookHandler() route verify Standard Webhooks signatures (svix) using the configured webhookSigningSecret. A rejected signature returns 401 with resend.webhook_signature_mismatch:<reason>, where the reason is a @spacetimedb/crypto errors code such as crypto.timestamp_outside_tolerance. signatureHeader and timestampHeader are stored on resend_webhook_event for forensic replay.
Tagging
userId / orgId are extracted from Resend tags and indexed for per-user / per-org listing.
send_emailtakestagsJsonas a JSON string in the array form Resend's send API expects:[{"name":"userId","value":"u_123"}].- Resend webhook payloads carry tags in object form:
{"userId": "u_123", "orgId": "o_456"}.
Integration testing
# Build + publish + event paths, idempotency, replay, signed-type checks, and authorization checks
pnpm run test:smokeThe smoke test publishes only to the dedicated resend-ts-smoke-test database.
For real Resend test-mode:
# Bootstrap once with your real key:
spacetime call --server http://127.0.0.1:3000 spacetime-resend set_resend_config '"re_..."' null '{"some":"[email protected]"}'
# Then send to one of Resend's test addresses (delivered@/bounced@/complained@):
spacetime call --server http://127.0.0.1:3000 spacetime-resend send_email \
null \
'["[email protected]"]' \
'"Test from SpacetimeDB"' \
'{"some":"<p>Hello.</p>"}' \
null null null null \
'{"some":"[{\"name\":\"userId\",\"value\":\"u_123\"}]"}' \
null null nullThe standalone module has no HTTP route. To receive webhooks from Resend, mount the submodule in a host module that registers makeResendWebhookHandler() on a router, as the example does at /webhook/resend. Expose the database through a public tunnel such as ngrok and register https://<tunnel>/v1/database/<database>/route/webhook/resend in Resend's dashboard with the same whsec_... you passed to set_resend_config.
Testing
pnpm test
pnpm run lintLicense
Apache-2.0. See the license.
