Building blocks
The kit sends its own account mail (sign-in links, password resets, address
verification, security notices, organization invitations) and gives you
deliverEmail for mail of your own. You work here when you set up sending for
a deploy, change how the mails look or read, send product or marketing mail, or
plug in another provider.
How it works
- A mail is an
EmailMessage:to,subject,html,textand acategory. OptionalreplyToreplaces the Reply-To on that mail alone, andlogSubjectis logged in place of a subject that holds a sender's own words. The kit's own mails come fromrenderEmail, which fills a compiled template fromlayers/kit/emails/(Licensees only) with themailcopy of the recipient's language catalogue, and declares that language and its direction. deliverEmail(event, message)inlayers/kit/server/email/index.ts(Licensees only) checks the category. A product or marketing mail goes out only to an account that has proven its address and still accepts that category, and getsList-Unsubscribeheaders.- It hands the mail to each configured provider in
email.providersorder. A failure the provider marks retryable gets one more try on the same provider, then the next provider gets the mail. Resend counts a send it has no answer to within ten seconds as such a failure. - When every provider refuses and at least one failure was transient, the
mail goes to the
emailjob on the queue (Background jobs). OtherwisedeliverEmailthrows a 502. Pass{ queueRetry: false }as its third argument to get the 502 instead of the queue, as the contact form does, so a mail never outlives the request that sent it.
Set up sending
Every mail is sent from mailboxes.hello on the site's domain, such as
hello@example.com, and carries the same address as its Reply-To
(Configuration). Create
that mailbox and onboard its domain before you deploy
(Deployment). A provider counts as
configured when there is a sender and the provider has what it needs:
| Provider | Needs | Setup |
|---|---|---|
cloudflare | The send_email binding named EMAIL in wrangler.jsonc | Onboard the sending domain once: pnpm exec wrangler email sending enable <domain> |
resend | NUXT_EMAIL_RESEND_API_KEY | resend.com, API Keys. Verify the sending domain under Domains first |
The shipped config lists cloudflare alone, and wrangler.jsonc already
declares its binding. For Resend, or Resend as a fallback:
email: {
enabled: true,
providers: ['cloudflare', 'resend'],
},
NUXT_EMAIL_FROM_NAME=Example
NUXT_EMAIL_RESEND_API_KEY=re_...
Every mailed link is built from NUXT_SITE_URL, and the mailboxes take their
domain from it, so a deploy needs that too (Deployment).
While the mailboxes have no domain, as on *.workers.dev, there is no sender.
Outside pnpm dev, the Worker logs at boot what is missing, and a send with no
configured provider answers 501.
NUXT_EMAIL_FROM and NUXT_EMAIL_REPLY_TO replace the sender and the
Reply-To. Both are optional, and the boot check names each one set to another
address than hello@. With only NUXT_EMAIL_FROM set, every mail still
replies to hello@. There is no noreply address: a reply to one bounces or
goes unread, and undeliverable replies hurt the domain's sender reputation.
Mail in local development
With NUXT_EMAIL_FROM unset, pnpm dev sends nothing and prints each mail's
recipient, subject and text to the terminal, links included. It never sends from
hello@, so the sign-in link stays there. Set NUXT_EMAIL_FROM and mail goes
to the providers, with no Reply-To unless NUXT_EMAIL_REPLY_TO is set. Resend
sends for real; the cloudflare binding runs in Wrangler's local simulator
unless you add "remote": true to it in wrangler.jsonc.
Send your own mail
Build the message yourself and state its category:
import { deliverEmail } from '#layers/kit/server/email'
await deliverEmail(event, {
to: user.email,
subject: 'Exports are here',
html: '<p>You can now export any report as CSV.</p>',
text: 'You can now export any report as CSV.',
category: 'product',
})
| Category | Use it for | Refusable | Unsubscribe link |
|---|---|---|---|
transactional | Mail the recipient's own action asked for | no | no |
product | News about the product the recipient already uses | yes | yes |
marketing | Offers and announcements | yes | yes |
Product and marketing mail, the elective kinds, is sent only when the address
belongs to an account that has proven it, has not opted out of that category,
is not banned and is not scheduled for deletion. Otherwise deliverEmail
returns without sending and without an error. An account that never confirmed
its address, such as one a guest checkout opened, gets elective mail once a
verification link, a magic link or a password reset proves it. The queue asks
the same question again before each retry, so an opt-out made while the mail
waited still wins.
Don't build elective mail with renderEmail: it always marks its mail
transactional. For a layout of your own, add emails/<name>.vue and read its
compiled HTML from emailTemplates in #email-templates, keyed by file name,
then fill its placeholders yourself. For a template that declares {lang} and
{dir} as the kit's do, EMAIL_LANGUAGES from
#layers/kit/server/email/copy holds each locale's lang and dir, keyed by
its code.
Start every link in the mail with requireLinkBase(event), the site's origin
from NUXT_SITE_URL. It works on the event a job, listener or task receives
too, so a mail sent from the queue builds its links the way a route does. Under
pnpm dev with no NUXT_SITE_URL it answers the request's own origin, or
http://localhost:3000 on such an event.
Unsubscribe links
Every elective mail carries List-Unsubscribe and List-Unsubscribe-Post
headers pointing at /api/email/unsubscribe?token=…, which gives Gmail and
Outlook a one-click unsubscribe. The token is one per account and category,
kept in email_unsubscribe_tokens, and never expires.
- A GET shows a page with one Unsubscribe button, so mail scanners that open links on delivery unsubscribe nobody. Only a POST records the opt-out.
- The opt-out is a timestamp on the user row,
email_product_opt_out_atoremail_marketing_opt_out_at. A repeat keeps the first time. - The page copy is the
unsubscribesection of each language's catalogue, changed the way the mail copy is.
Signed-in users switch both categories on /dashboard/settings, through
PATCH /api/account/email-preferences with product and marketing booleans
(true is subscribed).
Change how the mails look
The kit's layouts are Vue files in
layers/kit/emails/(Licensees only), written with Maizzle's components
and Tailwind classes. Maizzle compiles them, and yours in
emails/<name>.vue, to inlined HTML when Nuxt starts and at build, and the
Worker ships only the compiled strings.
email-change-notice.vue carries the security notices: emailChangeNotice,
emailMovedNotice, the passkeyAddedNotice, totpEnabledNotice and
oauthConnectedNotice the account's address gets when a passkey, two-factor
or a provider is added, and the secondFactorClearedNotice it gets when staff
turn two-factor off. org-invitation.vue carries the invitation, and
transactional.vue every other kind. That mapping is
TEMPLATE_FOR_KIND in
layers/kit/server/email/templates.ts(Licensees only),
which the kit imports by path, so a kit mail changes layout only through the
template it already uses.
To restyle one, copy the kit's file to the same name in your emails/, such as
emails/transactional.vue. Yours replaces the kit's, and pnpm kit:update
names it whenever the kit changes its own
(Updating from the kit).
A template holds single-brace placeholders that renderEmail fills with
escaped values: {body}, {cta}, {link} and {ignore} with the mail's copy,
and {lang} and {dir} with the language and direction of its locale, which
the kit's templates declare as <Html lang="{lang}" dir="{dir}"> and
<Body dir="{dir}">. The language is the locale's language, and the
direction is the one the app's pages take for it
(Languages). Write the placeholders exactly
like that, not as Vue's {{ }}.
To add a template for mail of your own, create emails/<name>.vue under a name
the kit does not use. It appears in #email-templates under its file name,
typed. Unit suites read #email-templates from
layers/kit/test/unit/email-templates.stub.ts(Licensees only),
which holds the kit's three names and none of yours.
The build fails when a template compiles to under 512 bytes, and
layers/kit/test/unit/email-templates.test.ts checks every compiled template,
yours included, for a doctype, the four copy placeholders and inlined styles.
It holds only the kit's own templates to {lang} and {dir}, so one of yours
that writes a fixed lang still passes.
Change the wording
Each language's catalogue holds a subject, body, cta and ignore per kind
under mail, such as mail.magicLink.subject. To reword one, put its key in
your i18n/locales/<file>, which is merged over the kit's catalogue of that
name (Languages):
{
"mail": {
"magicLink": {
"subject": "Your Acme sign-in link"
}
}
}
A key a language lacks takes the default locale's text, then the kit's English.
Placeholders such as {minutes} and {date} use the same brace syntax as the
rest of the catalogue, and one with no value is left as written. Mail copy is
printed without vue-i18n, so write a | or @ meant as text as {'|'} or
{'@'}; the build refuses, naming the key, any other vue-i18n syntax in it
(Languages). Mail goes out in the requester's
locale; invitations, and the mail the customers page's support actions send,
use i18n.defaultLocale. An unknown locale falls back to the default locale.
The build reads mail once, so restart pnpm dev after changing it.
A language you add takes its mail copy in its own catalogue.
layers/kit/test/unit/i18n-locales.test.ts names each key it still lacks, and
layers/kit/test/unit/email-copy.test.ts fails when its mail copy uses other
placeholders than the default locale's.
Add a provider
Drop a file at server/email/adapters/<id>.ts. The file name is the provider id
and the default export is an EmailAdapter.
server/email/adapters/postmark.ts:
import type { EmailAdapter } from '#layers/kit/server/email/types'
const postmark: EmailAdapter = {
id: 'postmark',
async send(message, sender, config) {
let res: Response
try {
res = await fetch('https://api.postmarkapp.com/email', {
method: 'POST',
headers: {
'X-Postmark-Server-Token': config.key,
'Content-Type': 'application/json',
},
signal: AbortSignal.timeout(10_000),
body: JSON.stringify({
From: sender.fromName
? `${sender.fromName} <${sender.from}>`
: sender.from,
To: message.to,
Subject: message.subject,
HtmlBody: message.html,
TextBody: message.text,
...(sender.replyTo ? { ReplyTo: sender.replyTo } : {}),
Headers: Object.entries(message.headers ?? {}).map(
([Name, Value]) => ({ Name, Value }),
),
}),
})
} catch (error) {
return { ok: false, reason: String(error), retryable: true }
}
if (res.ok) return { ok: true }
return {
ok: false,
reason: `${res.status} ${await res.text()}`,
retryable: res.status === 429 || res.status >= 500,
}
},
}
export default postmark
Then list it and name its credential:
email: {
enabled: true,
providers: ['postmark'],
adapters: { postmark: { credentials: ['apiKey'] } },
},
That reads NUXT_EMAIL_POSTMARK_API_KEY. A credential named apiKey arrives
as config.key; every declared credential is also in config.credentials.
Without an adapters entry, the whole block is one JSON variable, such as
NUXT_EMAIL_POSTMARK='{"apiKey":"…"}'.
- Return a result instead of throwing.
retryable: trueearns one repeat on the same provider; never set it for a 4xx. - Give the request a deadline, as the example's
signaldoes. The next provider gets the mail only once yours returns, so a provider that never answers holds the send, and the request behind it, until the runtime cuts it. - The id must be one lowercase word, and not
from,fromNameorreplyTo. The build refuses both. - A file named
resend.tsorcloudflare.tsreplaces the shipped adapter, and the build logs which file won. - Restart
pnpm devafter adding the file so the id typechecks.
Turn email off
Set email.enabled: false. No adapter or template is bundled, and the
password-reset routes are not registered. The build refuses it while
auth.emailVerification (with password sign-in), orgs.invitations or
account.deletionGraceDays still needs mail. With auth.primary: 'passwordless' the build only warns, and magic-link sign-in then fails.
Configuration
| Key or variable | Where | Default | What it does |
|---|---|---|---|
email.enabled | starter.config.ts | true | Bundles the providers and compiles the templates. |
email.providers | starter.config.ts | ['cloudflare'] | Providers in delivery order. Later ones only see a failed send. |
email.adapters | starter.config.ts | none | Credential names for an adapter you added. |
mailboxes.hello | starter.config.ts | 'hello' | The sender and Reply-To of every mail, on the mailboxes' domain. |
NUXT_EMAIL_FROM | env | unset | Replaces hello@ as the sender. Under pnpm dev, turns sending on. |
NUXT_EMAIL_FROM_NAME | env | unset | Display name inboxes show. |
NUXT_EMAIL_REPLY_TO | env | unset | Replaces hello@ as the Reply-To. |
NUXT_EMAIL_RESEND_API_KEY | env | unset | Resend API key. |
NUXT_EMAIL_<ID>_<KEY>, NUXT_EMAIL_<ID> | env | unset | An added adapter's credentials, one per key or the block as JSON. |
send_email binding EMAIL | wrangler.jsonc | declared | The cloudflare provider. The build fails without it while listed. |
Good to know
- The kit's mail, sign-in links included, replies to
hello@unlessNUXT_EMAIL_REPLY_TOsays otherwise, so that mailbox is public. A privateNUXT_CONTACT_ADDRESSstays offNUXT_EMAIL_FROMandNUXT_EMAIL_REPLY_TO(Contact): anyone can ask for a sign-in mail to their own inbox. - On the Workers Free plan, Cloudflare Email Sending delivers only to
addresses verified in your account, so sign-up and reset mail reaches nobody
else. List
resendwith its key on Free. renderEmailescapes the copy it fills in. HTML you build yourself goes out as written, so escape any value a user typed.- Cloudflare refuses a header name that is not on its allowlist unless it
starts with
X-. Name custom headersX-…. - Put padding on a
Sectioninside<Body>, never on<Body>: it is 100% wide, and padding it makes Gmail scroll sideways. - Templates compile when Nuxt starts, so restart
pnpm devto see an edit to one.
A link with a lock opens the kit’s private repository, which every licensee can read.