SMS
@dotpress/sms sends SMS through interchangeable providers: Twilio, Telnyx, Vonage, OVHcloud, Brevo and Amazon SNS. Every provider calls its API with fetch: no SDK, no dependency. It works in a route, a worker or a script.
Sending
to is a phone number in E.164 format: +, the country code, then the number, without spaces. Normalize the numbers when you store them: send() rejects any other format, without the number in the error, as errors end up in logs.
from is the sender, required: a phone number in E.164 format, a short code or an alphanumeric sender ID (Acme, 11 characters at most), as your provider and the destination country accept. send() takes a from that replaces the default one.
send() returns the messageId given by the provider. createSms() also takes a logger that logs each sent message, without the number nor the text.
Second factor of the auth
The client fits the sms option of createAuthMessages() of @dotpress/auth/messages, which sends the codes of the SMS second factor (mfa.sms). The auth package does not depend on this one: any object with a send({ to, text }) method fits.
Providers
Switching provider changes one line: the calls stay the same. A provider is an object with a name and a send(message) method: write your own for another service. The settings of each provider are in the SMS reference.
The console provider is for development. In production, a missing provider configuration must fail at startup: falling back to the console would lose every message silently, login codes included.
Amazon SNS
The provider signs its requests itself: it has no AWS credential chain. Pass the credentials, or a function returning them, called for each message. A credential provider of the AWS SDK fits, and refreshes temporary credentials:
On AWS Lambda, the environment holds the credentials of the role: { accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, sessionToken: process.env.AWS_SESSION_TOKEN }. The role needs the sns:Publish permission. A new account sends in the SMS sandbox, to verified numbers only, until AWS moves it to production.
Testing
The memory provider keeps the messages:
outbox.sent lists the messages, clear() empties it.
Errors
Sending is neither queued nor retried. For messages that must arrive despite a provider outage, send them from an event listener. See the SMS reference for every option.