Notify
Modules send email, such as a sign-in link or a receipt, without choosing an email service. Notify is where your app picks how email, SMS, push and simple notifications are delivered, per environment. For emails designed with Vue components, add Email Templates on top.
The package is @frigear-nu/notify. In-app toasts are not part of it: use
useToast() from Nuxt UI.
What you get
- Composables and helpers.
- Server functions that send an email, an SMS, a push notification or a simple notification, auto-imported in Nitro.
- A
logdriver that prints each notification instead of sending it. On by default. - Email drivers for Resend, Amazon SES and Cloudflare Email Service, or a driver file of your own. Opt-in.
- A push driver slot that Push fills when it is installed (FCM and APNs to the users' devices).
notifyUser, which sends one user a message on the channels they chose for its topic, and the topic registry modules declare those topics in. See Notifying a user.
- Emails. None of its own. It sends what other modules build.
modules. Auth (server
mode), Users, Preferences, Forms,
Subscriptions, Email Templates and the modules that send with notifyUser install
Notify.
Optional:Email Templates, to render emails from Vue templates.
Push, to deliver push notifications to the users' devices.
Preferences, so users choose their channels per topic.Quick setup
Install the module
pnpm add @frigear-nu/notify
Configure it in nuxt.config.ts
List Notify in modules only to configure it. This setup sends email through Resend and SMS through your own driver:
export default defineNuxtConfig({
modules: ['@frigear-nu/notify'],
notify: {
email: { driver: 'resend' },
sms: { driver: '~/server/utils/twilio-sms-driver' },
simple: { driver: 'log' },
},
})
nuxt.config.ts. Anyone who has them can send email as you.Set the environment variables
Set NUXT_NOTIFY_EMAIL_FROM and the credentials of your email driver, listed under
Environment variables.
log driver, the server console prints [notify] Dispatching notification: and
the notification. With a real driver, the email arrives.Options
Options go under the notify key. Each notification type has its own driver, and only the configured driver is
loaded.
| Option | Type | Default | Purpose |
|---|---|---|---|
email.driver | 'log' | 'resend' | 'ses' | 'cloudflare' | 'cloudflare-binding' | string | 'log' | A built-in name, or a path to a file whose default export is an EmailDriver. |
sms.driver | 'log' | string | 'log' | 'log', or a path to a file whose default export is an SMSDriver. With SMS installed the default is its sendSms. notifyUser passes meta.source (the topic's module) and meta.topic; a direct dispatchSMSNotification should pass its own meta.source. |
simple.driver | 'log' | string | 'log' | 'log', or a path to a file whose default export is a SimpleDriver. |
push.driver | 'log' | string | 'log', or Push's driver when Push is installed | 'log', or a path to a file whose default export is a PushDriver. A value you set wins over Push's. |
email.driver set to a built-in name only sets the default. NUXT_NOTIFY_EMAIL_DRIVER overrides it at runtime. A
path to a file is fixed at build time.
Environment variables
The built-in email drivers are read from runtimeConfig.notify.email at runtime, so each environment can use another
service without a rebuild. They use plain fetch, with no dependencies. SES requests are signed with AWS Signature
Version 4 through Web Crypto.
| Variable | Used by | Purpose |
|---|---|---|
NUXT_NOTIFY_EMAIL_DRIVER | all | log (default), resend, ses, cloudflare or cloudflare-binding. Any other value throws when sending. |
NUXT_NOTIFY_EMAIL_FROM | resend, ses, cloudflare, cloudflare-binding | The sender, such as Frigear <no-reply@frigear.nu>. |
NUXT_NOTIFY_EMAIL_RESEND_API_TOKEN | resend | API token. |
NUXT_NOTIFY_EMAIL_SES_REGION | ses | AWS region, such as eu-west-1. Uses the SES v2 API. |
NUXT_NOTIFY_EMAIL_SES_ACCESS_KEY_ID | ses | Access key id. |
NUXT_NOTIFY_EMAIL_SES_SECRET_ACCESS_KEY | ses | Secret access key. |
NUXT_NOTIFY_EMAIL_SES_SESSION_TOKEN | ses | Optional, for temporary credentials. |
NUXT_NOTIFY_EMAIL_CLOUDFLARE_ACCOUNT_ID | cloudflare | Cloudflare account id (Email Service). |
NUXT_NOTIFY_EMAIL_CLOUDFLARE_API_TOKEN | cloudflare | API token. |
NUXT_NOTIFY_EMAIL_BINDING_NAME | cloudflare-binding | The name of the Worker's send_email binding. Defaults to SEND_EMAIL. |
A missing credential fails the send, with an error that names the variable to set.
Cloudflare Workers binding
The cloudflare-binding driver sends through a send_email binding of the Worker, with no API token: it builds the
raw MIME message itself (UTF-8, base64 bodies, RFC 2047 encoded names and subjects) and hands it to
env.<binding>.send(new EmailMessage(from, to, raw)) of cloudflare:email, once per to and cc recipient. Because
it writes the message, it sets the Message-ID (<random>@<sender domain>) and returns it, so a caller can thread
answers by it (the inbox does). It runs only on Cloudflare Workers; elsewhere the send fails.
{
"send_email": [{ "name": "SEND_EMAIL" }]
}
With Nitro, add the binding under nitro.cloudflare.wrangler.send_email. What Cloudflare lets the binding send to:
- Verified destinations only, unless the sender's domain is onboarded to Cloudflare Email Service (Email Sending).
Without it, a recipient that is not a verified destination address of Email Routing is refused
(
E_RECIPIENT_NOT_ALLOWED), and some plans only ever allow verified destinations (E_RECIPIENT_PLAN_RESTRICTED). - The sender's domain must be set up for Email Sending on the account (
E_SENDER_DOMAIN_NOT_AVAILABLE,E_SENDER_DOMAIN_NOT_CONFIGUREDotherwise). The binding can restrict senders and recipients itself (allowed_sender_addresses,allowed_destination_addresses). - See Send emails from Workers
for the current rules. Cloudflare recommends its structured
send()for new code; this driver keeps the rawEmailMessageform, which Cloudflare still supports, so that the message carries its own Message-ID and threading headers.
To send only some mail through it, pick it per send: dispatchEmailNotification(notification, { driver: 'cloudflare-binding' }) (the inbox's email.outbound does this for its replies).
Server
The dispatch functions and the definers are auto-imported in server code wherever the module is installed.
| Function | Signature |
|---|---|
dispatchEmailNotification | (notification: EmailNotification, options?: { driver? }) => Promise<EmailSendResult | undefined> |
dispatchSMSNotification | (notification: SMSNotification) => Promise<void> |
dispatchSimpleNotification | (notification: SimpleNotification) => Promise<void> |
dispatchPushNotification | (notification: PushNotification) => Promise<PushDispatchResult | undefined> |
defineEmailNotification, defineSMSNotification, defineSimpleNotification, definePushNotification | Typed helpers that return the notification unchanged. |
defineEmailDriver, defineSMSDriver, defineSimpleDriver, definePushDriver | Typed helpers that return the driver unchanged. |
await dispatchEmailNotification({
to: user.email,
subject: 'Welcome!',
body: '<p>Thanks for signing up.</p>',
text: 'Thanks for signing up.',
})
await dispatchSMSNotification({
to: user.phone,
body: 'Your verification code is 123456.',
})
await dispatchSimpleNotification({
title: 'New signup',
text: `${user.email} just signed up.`,
})
await dispatchPushNotification({
userIds: [user.id],
title: { da: 'Ny besked', en: 'New message' },
body: 'Open the app to read it.',
url: '/inbox',
})
dispatchEmailNotification resolves to what the driver reports: { messageId } from cloudflare-binding, undefined
from the others. options.driver sends this one email through another built-in driver (log, resend, ses,
cloudflare, cloudflare-binding), configured from the same NUXT_NOTIFY_EMAIL_* variables; the notify:email hook
runs as always.
Push
dispatchPushNotification sends to every device of userIds that the push driver knows. Notify stores no devices:
with Push installed, Push is the driver (FCM and APNs to the devices it stores), and the
result says how many devices took it ({ sent, failed, revoked }). With the log driver the notification is only
logged and the result is undefined. A list of no users resolves to { sent: 0, failed: 0 } without calling the
driver. A driver error reaches the caller.
title and body are a text, or one text per locale ({ da, en }); a driver that knows each device's locale picks
it, Push falls back to en.
Templates
Notify renders no templates itself. dispatchEmailNotification calls the notify:email hook before the driver runs,
where Email Templates renders notification.template. Without a renderer, subject and body are sent as built.
Types
The types are exported from @frigear-nu/notify/types. The package root re-exports the notification, driver and
ModuleOptions types.
interface EmailNotification<M = NotificationMeta> {
to: string | string[]
subject: string
/** HTML body. */
body: string
/** Optional plain-text body. */
text?: string
/** The sender of this email, instead of the configured `from`. */
from?: string
/** Address replies go to (the `Reply-To` header). */
replyTo?: string
/** `Cc` recipients. */
cc?: string | string[]
/** Extra headers, such as `List-Unsubscribe`. */
headers?: Record<string, string>
/** Template to render instead of subject/body/text, when a renderer is installed. */
template?: { name: string, props?: Record<string, unknown>, locale?: string }
meta?: M
}
interface SMSNotification<M = NotificationMeta> {
to: string | string[]
body: string
meta?: M
}
interface PushNotification<M = NotificationMeta> {
userIds: number[]
/** A text, or one text per locale. */
title: string | Record<string, string>
body: string | Record<string, string>
/** Where the app goes when the notification is opened. */
url?: string
/** Extra string data delivered with the notification. */
data?: Record<string, string>
meta?: M
}
/** What a push driver may answer; the `log` driver answers nothing. */
type PushDispatchResult = { sent: number, failed: number, revoked?: number }
interface SimpleNotification<M = Record<string, unknown>> {
title: string
text: string
/** Optional URL to open when the notification is clicked. */
url?: string
meta?: M
}
type NotificationMeta<AdditionalMeta = Record<string, unknown>> = { driver?: string } & AdditionalMeta
/** What an email driver may report; `void` is fine. `messageId` is the Message-ID header it set, without brackets. */
type EmailSendResult = { messageId?: string }
type EmailDriver = (notification: EmailNotification) => Promise<EmailSendResult | void> | EmailSendResult | void
type SMSDriver = (notification: SMSNotification) => Promise<void> | void
type SimpleDriver = (notification: SimpleNotification) => Promise<void> | void
type PushDriver = (notification: PushNotification) => Promise<PushDispatchResult | void> | PushDispatchResult | void
Custom driver
A driver is a function that delivers one notification. Point the driver option at a file whose default export is that function:
import type { EmailDriver } from '@frigear-nu/notify/types'
const sendWithResend: EmailDriver = async (notification) => {
// call your provider with notification.to / cc / from / subject / body / text / replyTo
}
export default sendWithResend
A driver may return { messageId }, the Message-ID header it set itself (only that, never a provider's own id), or
nothing. Returning nothing stays valid, so existing drivers need no change.
cc is optional. The built-in resend, ses and cloudflare drivers send it as the provider's cc list (a single
address becomes a list), and log logs it with the rest. A driver whose transport has no cc may ignore it; say so where
you document the driver, because callers such as the inbox use it to keep the people a person copied in the reply.
from is optional. It replaces the configured sender (NUXT_NOTIFY_EMAIL_FROM) for one email, as a bare address
(support@inbox.example.org) or with a display name ("Support" <support@inbox.example.org>). The built-in resend
driver sends it as it is, ses with a non-ASCII display name RFC 2047 encoded (Støtte becomes
=?UTF-8?B?...?=), cloudflare sends a display name as its { address, name } form, cloudflare-binding writes it
into the message, and log logs it. The provider must have the address's domain verified for sending, or it refuses the email. The inbox uses it to
answer from a mailbox's own address. A custom driver that cannot change the sender may ignore it; say so where you
document the driver.
headers is optional too. The built-in drivers send it as the provider's custom headers (SES as Name/Value pairs of
the simple content), and log logs it. Use it for headers such as List-Unsubscribe and List-Unsubscribe-Post
(one-click unsubscribe, RFC 8058), which mailbox providers expect on bulk mail. A provider never lets you set the
headers it sets itself (From, To, Subject, Message-ID, Date), and Cloudflare accepts only the headers on its
allowlist plus X- headers: any other header makes it reject the whole send. The allowlist has the threading headers
(In-Reply-To, References) and the list headers (List-Unsubscribe, List-Unsubscribe-Post, List-Id, ...). A driver whose transport has no custom
headers may ignore them.
Store types
@frigear-nu/notify/types also exports StoredNotification and NotificationStore, a contract with put, get,
list and delete for keeping notifications. Nothing in the module uses a store yet, and dispatch records nothing.
Notifying a user
The dispatchers above send what you address. notifyUser sends one user a message on the channels they chose for its
topic: email, SMS and push, each through the dispatcher of that channel.
| Function | Signature |
|---|---|
notifyUser | (userId: number, input: NotifyUserInput) => Promise<NotifyUserResult> |
registeredNotificationTopics, findNotificationTopic | The registered topics, and one by id. |
readNotificationChannels | (userId) => Promise<NotificationChannelsDto>: every topic with what applies to the user. |
saveNotificationChannels | (userId, changes) => Promise<void>: stores the channels set, per topic and channel; channels never set follow the topic's defaults. |
Declare your topics
A topic is one kind of message a user can choose channels for, such as shift reminders. Register yours in your
module's setup() with extendNotificationTopics from @frigear-nu/notify/utils, and list Notify in
moduleDependencies:
import { extendNotificationTopics } from '@frigear-nu/notify/utils'
extendNotificationTopics(nuxt, [{
id: 'shifts.reminder',
label: { da: 'Vagtpåmindelser', en: 'Shift reminders' },
description: { da: 'En påmindelse før dine vagter starter.', en: 'A reminder before your shifts start.' },
defaults: { email: true, sms: false, push: true },
channels: ['email', 'sms', 'push'],
}])
idis lower case words joined by.,_or-, at most 100 characters. The choices are stored under it.defaultssays what applies until the user chooses, one boolean per channel. All three are required. A user's choices store only the channels they changed; every other channel of the topic followsdefaults, so changing a default later reaches everyone who never touched that channel. Keepsmsoff by default: a text costs money and goes only to people who turned it on. Every topic of the platform's modules does so, so an SMS reaches a user only after they chose it on the account page.channelslists the channels the topic offers (all three when left out). A channel it does not offer is never sent.labelanddescriptionare a text or one text per locale;labelKeyanddescriptionKeyname i18n keys tried first.
The order between modules does not matter: the registry is read once every module is set up. A topic registered again under the same id replaces the earlier one. A malformed topic fails the build.
Send
const result = await notifyUser(userId, {
topic: 'shifts.reminder',
email: { subject: 'Shift tomorrow', body: '<p>You work at 18:00.</p>', template: { name: 'shifts-reminder', props } }, // also text, from, replyTo, headers, meta
sms: { body: { da: 'Vagt i morgen kl. 18', en: 'Shift tomorrow at 18:00' } },
push: { title: 'Shift tomorrow', body: 'You work at 18:00.', url: '/shifts/1' },
})
// { channels: ['email', 'push'], skipped: { sms: 'disabled' } }
A channel goes out when the topic offers it, the user's choice (or the topic's default) has it on, you gave content for
it and the user can be reached on it. The email goes to the user's address, the SMS to their number, and the push to
their devices through dispatchPushNotification. skipped says why a channel did not go out: disabled (off for the
topic), no_content, unavailable (no address, no number, no device took the push) or failed. A driver that reports
nothing, such as log, counts as sent.
An error on one channel is logged and does not stop the others; notifyUser does not throw for it. An unknown topic
throws, and so does a store that fails: when findRecipient or readChoices throws (a database error), notifyUser
rejects before any channel is sent, rather than send on defaults the user may have turned off. Catch and log it where
you call it from a hook or a task, so your own work goes on.
Where contacts and choices come from
Notify stores neither. Two modules register them, and Notify reads them through these interfaces (exported from
@frigear-nu/notify/types):
| Interface | Registered by | With setX(nuxt, path) | Without one |
|---|---|---|---|
NotifyRecipientStore: findRecipient(userId) answers { email, phone, locale } or null | Users | setNotifyRecipientStore | notifyUser sends nothing and logs a warning. |
NotifyChoicesStore: readChoices(userId), writeChoices(userId, choices); writeChoices merges the channels given per channel into what it reads right before writing | Preferences | setNotifyChoicesStore | The topics' defaults apply to everyone, and choices cannot be saved. |
path is a file whose default export is the store. The first registration wins. The recipient's locale picks the SMS
text and fills in the email template's locale when it has none.
Hooks
A renderer such as Email Templates listens to these hooks.
| Hook | When | Payload |
|---|---|---|
notify:email (Nitro) | An email is about to go to the driver. | { notification }, replaceable |
notify:email:templates (Nuxt) | A renderer collects the template folders that modules ship. | EmailTemplateSource[]: push { dir } |
Next steps
- Email Templates – render your emails from Vue components with your branding.
- Send an email – send your first email from a server route.
- Deployment – set the driver's secrets on your hosting platform.