Skip to content

Building blocks

Email

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

  1. A mail is an EmailMessage: to, subject, html, text and a category. Optional replyTo replaces the Reply-To on that mail alone, and logSubject is logged in place of a subject that holds a sender's own words. The kit's own mails come from renderEmail, which fills a compiled template from layers/kit/emails/(Licensees only) with the mail copy of the recipient's language catalogue, and declares that language and its direction.
  2. deliverEmail(event, message) in layers/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 gets List-Unsubscribe headers.
  3. It hands the mail to each configured provider in email.providers order. 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.
  4. When every provider refuses and at least one failure was transient, the mail goes to the email job on the queue (Background jobs). Otherwise deliverEmail throws 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:

ProviderNeedsSetup
cloudflareThe send_email binding named EMAIL in wrangler.jsoncOnboard the sending domain once: pnpm exec wrangler email sending enable <domain>
resendNUXT_EMAIL_RESEND_API_KEYresend.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',
})
CategoryUse it forRefusableUnsubscribe link
transactionalMail the recipient's own action asked fornono
productNews about the product the recipient already usesyesyes
marketingOffers and announcementsyesyes

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.

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_at or email_marketing_opt_out_at. A repeat keeps the first time.
  • The page copy is the unsubscribe section 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: true earns one repeat on the same provider; never set it for a 4xx.
  • Give the request a deadline, as the example's signal does. 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, fromName or replyTo. The build refuses both.
  • A file named resend.ts or cloudflare.ts replaces the shipped adapter, and the build logs which file won.
  • Restart pnpm dev after 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 variableWhereDefaultWhat it does
email.enabledstarter.config.tstrueBundles the providers and compiles the templates.
email.providersstarter.config.ts['cloudflare']Providers in delivery order. Later ones only see a failed send.
email.adaptersstarter.config.tsnoneCredential names for an adapter you added.
mailboxes.hellostarter.config.ts'hello'The sender and Reply-To of every mail, on the mailboxes' domain.
NUXT_EMAIL_FROMenvunsetReplaces hello@ as the sender. Under pnpm dev, turns sending on.
NUXT_EMAIL_FROM_NAMEenvunsetDisplay name inboxes show.
NUXT_EMAIL_REPLY_TOenvunsetReplaces hello@ as the Reply-To.
NUXT_EMAIL_RESEND_API_KEYenvunsetResend API key.
NUXT_EMAIL_<ID>_<KEY>, NUXT_EMAIL_<ID>envunsetAn added adapter's credentials, one per key or the block as JSON.
send_email binding EMAILwrangler.jsoncdeclaredThe cloudflare provider. The build fails without it while listed.

Good to know

  • The kit's mail, sign-in links included, replies to hello@ unless NUXT_EMAIL_REPLY_TO says otherwise, so that mailbox is public. A private NUXT_CONTACT_ADDRESS stays off NUXT_EMAIL_FROM and NUXT_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 resend with its key on Free.
  • renderEmail escapes 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 headers X-….
  • Put padding on a Section inside <Body>, never on <Body>: it is 100% wide, and padding it makes Gmail scroll sideways.
  • Templates compile when Nuxt starts, so restart pnpm dev to see an edit to one.

A link with a lock opens the kit’s private repository, which every licensee can read.