elghaied

payload plugin sms

by elghaied
Notifications & messaging
v3
^3.0.0

Overview

Summary generated from the README

Adds a payload.sendSMS method backed by a provider adapter interface, with each provider shipped as a separate subpath export and its SDK as an optional peer dependency. It can create an sms-logs collection, show a dashboard widget and receive delivery-status webhooks. It targets Payload 3.x and requires recipient numbers in E.164 format.

Features

  • Adapters for Twilio, Telnyx, Plivo, Vonage and AWS SNS plus a mock adapter for tests
  • Optional sms-logs collection with status, cost, error and delivery timestamps
  • Delivery-status webhooks with signature verification and optional status history
  • Router adapter with tenant, country prefix, round-robin, random and failover routing
  • Dashboard widget with opt-in tenant scoping, plus onSend, onError and onStatus hooks
  • Bundled English and French translations

Use cases

  • Send a welcome text message from a collection hook when a user signs up
  • Route SMS per tenant or country prefix across several providers with failover
  • Track real delivery state of sent messages in the admin panel

From the author

Multi-provider SMS plugin for Payload CMS 3.x with Twilio, Telnyx, Plivo, Vonage, and AWS SNS adapters.

Installation

npm i @elghaied/payload-plugin-sms

7

Stars

0

Forks

0

Open Issues

5 months ago

Last Updated

81

Weekly Downloads

v0.5.0

npm Version

558.5 KB

Unpacked Size

0

Dependencies

GitHub stars

7+2 since Sep 6

Show data
GitHub stars by day (UTC)
DateStars
Dec 5, 20267
Dec 4, 20267
Dec 3, 20267
Dec 2, 20267
Dec 1, 20267
Nov 30, 20267
Nov 29, 20267
Nov 28, 20267
Nov 27, 20267
Nov 26, 20267
Nov 25, 20267
Nov 24, 20267
Nov 23, 20267
Nov 22, 20267
Nov 21, 20267
Nov 20, 20267
Nov 19, 20267
Nov 18, 20267
Nov 17, 20267
Nov 16, 20267
Nov 15, 20267
Nov 14, 20267
Nov 13, 20267
Nov 12, 20267
Nov 11, 20267
Nov 10, 20267
Nov 9, 20267
Nov 8, 20267
Nov 7, 20267
Nov 6, 20267
Nov 5, 20267
Nov 4, 20267
Nov 3, 20267
Nov 2, 20267
Nov 1, 20267
Oct 31, 20267
Oct 30, 20267
Oct 29, 20267
Oct 28, 20267
Oct 27, 20267
Oct 26, 20267
Oct 25, 20267
Oct 24, 20267
Oct 23, 20267
Oct 22, 20267
Oct 21, 20267
Oct 20, 20267
Oct 19, 20267
Oct 18, 20267
Oct 17, 20267
Oct 16, 20267
Oct 15, 20267
Oct 14, 20267
Oct 13, 20267
Oct 12, 20267
Oct 11, 20267
Oct 10, 20267
Oct 9, 20266
Oct 8, 20266
Oct 7, 20266
Oct 6, 20266
Oct 5, 20266
Oct 4, 20266
Oct 3, 20266
Oct 2, 20266
Oct 1, 20266
Sep 30, 20266
Sep 29, 20266
Sep 28, 20266
Sep 27, 20266
Sep 26, 20265
Sep 25, 20265
Sep 24, 20265
Sep 23, 20265
Sep 22, 20265
Sep 21, 20265
Sep 20, 20265
Sep 19, 20265
Sep 18, 20265
Sep 17, 20265
Sep 16, 20265
Sep 15, 20265
Sep 14, 20265
Sep 13, 20265
Sep 12, 20265
Sep 11, 20265
Sep 10, 20265
Sep 9, 20265
Sep 8, 20265
Sep 7, 20265
Sep 6, 20265
npm weekly downloads

64−3 since Sep 6

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 5, 202664
Dec 4, 202683
Dec 3, 202684
Dec 2, 202687
Dec 1, 202680
Nov 30, 202677
Nov 29, 202670
Nov 28, 202669
Nov 27, 202653
Nov 26, 202650
Nov 25, 202658
Nov 24, 202654
Nov 23, 202645
Nov 22, 202654
Nov 21, 202656
Nov 20, 202659
Nov 19, 202669
Nov 18, 202677
Nov 17, 202679
Nov 16, 202690
Nov 15, 202679
Nov 14, 202680
Nov 13, 202673
Nov 12, 202660
Nov 11, 202647
Nov 10, 202647
Nov 9, 202636
Nov 8, 202636
Nov 7, 202640
Nov 6, 202637
Nov 5, 202636
Nov 4, 202629
Nov 3, 202631
Nov 2, 202630
Nov 1, 202626
Oct 31, 202619
Oct 30, 202627
Oct 29, 202624
Oct 28, 202623
Oct 27, 202625
Oct 26, 202627
Oct 25, 202644
Oct 24, 202664
Oct 23, 202655
Oct 22, 202673
Oct 21, 202688
Oct 20, 202690
Oct 19, 202697
Oct 18, 202690
Oct 17, 202678
Oct 16, 202694
Oct 15, 202689
Oct 14, 202692
Oct 13, 202687
Oct 12, 202682
Oct 11, 202676
Oct 10, 202674
Oct 9, 202669
Oct 8, 202659
Oct 7, 202643
Oct 6, 202638
Oct 5, 202636
Oct 4, 202639
Oct 3, 202636
Oct 2, 202629
Oct 1, 202628
Sep 30, 202633
Sep 29, 202645
Sep 28, 202655
Sep 27, 202659
Sep 26, 202674
Sep 25, 202672
Sep 24, 2026100
Sep 23, 202699
Sep 22, 202684
Sep 21, 202676
Sep 20, 202673
Sep 19, 202665
Sep 18, 202676
Sep 17, 202678
Sep 16, 202690
Sep 15, 202696
Sep 14, 202693
Sep 13, 202698
Sep 12, 2026104
Sep 11, 202699
Sep 10, 202678
Sep 9, 202670
Sep 8, 202670
Sep 7, 202670
Sep 6, 202667

Each point is npm's rolling 7-day download count.

Health Score

53/100Good

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1249769132-root.svg)](https://payloaddirectory.dev/plugins/1249769132-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1249769132-root"><img src="https://payloaddirectory.dev/badge/1249769132-root.svg" alt="Payload Directory"></a>
Updated Jun 9, 2026Created May 26, 2026Published Jun 9, 2026

README

@elghaied/payload-plugin-sms

npm version npm downloads license

Multi-provider SMS plugin for Payload CMS 3.x. Send SMS through Twilio, Telnyx, Plivo, Vonage, or AWS SNS — and call payload.sendSMS(...) from anywhere.

Architecture mirrors @payloadcms/email-nodemailer: a thin core defines an adapter interface, and each provider ships as a separate subpath export with the SDK declared as an optional peer dependency.

Install

pnpm add @elghaied/payload-plugin-sms

Then install the SDK for your chosen provider:

pnpm add twilio                  # Twilio
pnpm add telnyx                  # Telnyx
pnpm add plivo                   # Plivo
pnpm add @vonage/server-sdk      # Vonage
pnpm add @aws-sdk/client-sns     # AWS SNS

Quick start (Twilio)

import { buildConfig } from 'payload'
import { smsPlugin } from '@elghaied/payload-plugin-sms'
import { twilioAdapter } from '@elghaied/payload-plugin-sms/twilio'

export default buildConfig({
  plugins: [
    smsPlugin({
      adapter: twilioAdapter({
        accountSid: process.env.TWILIO_ACCOUNT_SID!,
        authToken: process.env.TWILIO_AUTH_TOKEN!,
        defaultFrom: process.env.TWILIO_FROM!,
      }),
      collections: { logs: true },
      widgets: true,
    }),
  ],
})

Sending SMS

import type { CollectionConfig } from 'payload'

export const Users: CollectionConfig = {
  slug: 'users',
  auth: true,
  fields: [{ name: 'phone', type: 'text' }],
  hooks: {
    afterChange: [
      async ({ doc, req, operation }) => {
        if (operation === 'create' && doc.phone) {
          await req.payload.sendSMS({
            to: doc.phone,
            body: `Welcome ${doc.email}!`,
          })
        }
      },
    ],
  },
}

to must be E.164 (+ then 1–15 digits). from falls back to plugin defaultFrom, then adapter defaultFrom.

Adapters

Twilio

import { twilioAdapter } from '@elghaied/payload-plugin-sms/twilio'

twilioAdapter({
  accountSid: '...',
  authToken: '...',
  defaultFrom: '+15551234567',
  messagingServiceSid: 'MG...', // optional; supersedes `from`
})

Telnyx

import { telnyxAdapter } from '@elghaied/payload-plugin-sms/telnyx'

telnyxAdapter({
  apiKey: '...',
  defaultFrom: '+15551234567',
  messagingProfileId: '...', // optional
})

Plivo

import { plivoAdapter } from '@elghaied/payload-plugin-sms/plivo'

plivoAdapter({
  authId: '...',
  authToken: '...',
  defaultFrom: '+15551234567',
})

Vonage

Uses the legacy SMS API (key + secret). The Messages API (JWT-authenticated) is on the roadmap.

import { vonageAdapter } from '@elghaied/payload-plugin-sms/vonage'

vonageAdapter({
  apiKey: '...',
  apiSecret: '...',
  defaultFrom: '+15551234567',
})

AWS SNS

SNS has no per-message from. defaultFrom is sent as the AWS.SNS.SMS.SenderID attribute (region-dependent support).

import { awsSnsAdapter } from '@elghaied/payload-plugin-sms/aws-sns'

awsSnsAdapter({
  region: 'us-east-1',
  credentials: {                    // optional; falls back to default AWS credential chain
    accessKeyId: '...',
    secretAccessKey: '...',
  },
  defaultFrom: 'MYBRAND',           // sender ID
  smsType: 'Transactional',         // or 'Promotional'
})

Mock (tests)

import { mockAdapter } from '@elghaied/payload-plugin-sms/mock'

const adapter = mockAdapter({ defaultFrom: '+15550000000' })
adapter.messages  // array of sent messages
adapter.reset()   // clears it

Plugin options

OptionTypeDefaultNotes
adapterSMSAdapter—Required at runtime. Missing adapter → sendSMS throws.
defaultFromstring—Falls back to adapter's defaultFrom.
disabledbooleanfalseSkips registration; logs a warning.
collections.logsboolean | { slug?; admin?; includeContext?; statusHistory? }falseCreates an sms-logs collection. includeContext adds a JSON context field; statusHistory adds an append-only status-event array.
widgetsbooleantrueRegisters the dashboard widget when logs enabled.
tenantScoping{ field?: string; cookie?: string }— (off)Opt-in. Scopes the dashboard widget to the host's selected tenant. See Dashboard widget.
webhooks{ enabled; basePath?; statusCallbackUrl?; trustProxy?; verifySignature? }—Enables the delivery-status receiver + auto-derived callback. See Delivery-status webhooks.
onSend(args) => void | Promise<void>—Called after every successful send.
onError(args) => void | Promise<void>—Called when send fails. Original error is re-thrown.
onStatus(args) => void | Promise<void>—Called on every delivery-status webhook event (requires webhooks.enabled).

Logs collection

Enable with collections: { logs: true }. Schema:

FieldTypeNotes
totextRecipient
fromtextSender
bodytextareaMessage body
providertextAdapter name
statusselectqueued/sent/delivered/failed/unknown
providerMessageIdtextProvider's message id
costgroup{ amount, currency } when reported
errortextareaAdapter error message (if any)
errorCodetextProvider error code (from a failed-status webhook)
sentAtdateServer timestamp
deliveredAtdateSet when a webhook reports delivered
failedAtdateSet when a webhook reports failed
contextjsonPer-send metadata — only with includeContext: true
statusHistoryarrayAppend-only { status, occurredAt, errorCode } — only with statusHistory: true

deliveredAt / failedAt / errorCode / statusHistory are populated by delivery-status webhooks.

Read access requires a logged-in admin user. Create/update/delete from the admin panel are blocked — the plugin is the only writer.

Override the slug:

collections: { logs: { slug: 'audit-sms', admin: { group: 'Audit' } } }

Note: if you override the slug, set widgets: false — the bundled widget reads from sms-logs only.

Dashboard widget

When widgets: true and logs are enabled, the plugin registers an admin.dashboard.widgets entry that shows a 24h send count, the last 5 entries, and a link to the logs collection.

Disable with widgets: false.

Multi-tenant scoping

The plugin is single-tenant by design, so by default the widget queries sms-logs with the Local API's implicit overrideAccess: true and no tenant filter — it shows every row. In a multi-tenant host (e.g. @payloadcms/plugin-multi-tenant injecting a tenant field into sms-logs) that leaks other tenants' logs into the dashboard.

Opt in with tenantScoping to make the widget honor the host's tenant selector:

smsPlugin({
  adapter,
  collections: { logs: true },
  tenantScoping: { field: 'tenant', cookie: 'payload-tenant' }, // both optional; these are the defaults
})

When enabled and the logs collection actually has the configured field, the widget:

  • reads the selected tenant id from the cookie and adds where[field][equals]=<id> to both the 24h count and the recent-5 list, and
  • runs the queries with overrideAccess: false and the real request/user, so any read access control the host added to sms-logs is respected.

With no tenant selected ("all tenants"), it drops the tenant filter but still runs with overrideAccess: false, so the dashboard shows everything the current user is allowed to read. Omit tenantScoping, or leave the field off the collection, and the widget behaves exactly as before.

Router adapter (multi-provider)

For multi-tenant SaaS or geo-routing, wrap multiple adapters in a routerAdapter and decide per-send which one handles the message.

import { smsPlugin } from '@elghaied/payload-plugin-sms'
import { twilioAdapter } from '@elghaied/payload-plugin-sms/twilio'
import { telnyxAdapter } from '@elghaied/payload-plugin-sms/telnyx'
import { routerAdapter, byTenantLookup } from '@elghaied/payload-plugin-sms/router'

smsPlugin({
  adapter: routerAdapter({
    providers: {
      twilio: twilioAdapter({ accountSid, authToken }),
      telnyx: telnyxAdapter({ apiKey }),
    },
    route: byTenantLookup({
      collection: 'tenants',
      providerField: 'smsProvider',
      cacheMs: 60_000,
    }),
  }),
  collections: { logs: { includeContext: true } },
})

At the call site, attach the tenant id (and any per-tenant from):

await req.payload.sendSMS({
  to: customer.phone,
  from: tenant.smsFromNumber,
  body: '...',
  context: { tenantId: tenant.id },
})

The router is just another SMSAdapter. Single-provider users (smsPlugin({ adapter: twilioAdapter(...) })) are unaffected.

Route helpers

HelperUse
byTenantLookup({ collection, providerField, contextKey?, cacheMs?, fallback? })SaaS: read tenant id from message.context, fetch the doc, return its provider field
byCountryPrefix({ '+1': 'twilio', '+33': 'telnyx' }, { fallback? })Geo route by E.164 prefix; longest-prefix wins
byRoundRobin(['twilio-a', 'twilio-b'])Cycle across duplicate accounts
byRandom(['twilio-a', 'twilio-b'])Uniform random pick
withFailover(inner, ['fallback-a', 'fallback-b'])Wrap any route; on SMSProviderError, try the next provider in order

You can also write a route callback directly — it's just (args) => string \| string[] (or async).

context

SMSMessage.context is an opaque per-send map. It flows to the route function, the onSend/onError hooks (via args.message), and — when collections.logs.includeContext: true — into a context (JSON) field on the sms-logs collection.

Failover semantics

A route returning a single provider name calls that provider once. Returning an array ['a', 'b'] tries each in order on SMSProviderError; if all fail the router throws a single SMSProviderError whose .cause is an array of the individual errors. SMSValidationError is never retried.

Hooks (onSend, onError)

smsPlugin({
  adapter: twilioAdapter({ ... }),
  onSend: async ({ result, req }) => {
    console.log(`Sent ${result.id} via ${result.provider} to ${result.to}`)
  },
  onError: async ({ error, message, req }) => {
    console.error(`Failed to send to ${message.to}:`, error)
  },
})

Hook failures are logged but do not affect the SMS send result. req is undefined when called via payload.sendSMS (Payload's local API does not thread req through dynamic methods).

Errors

import { SMSValidationError, SMSProviderError } from '@elghaied/payload-plugin-sms'

try {
  await payload.sendSMS({ to: 'not-e164', body: 'hi' })
} catch (err) {
  if (err instanceof SMSValidationError) {
    // Bad input (E.164 fail, missing from, missing adapter)
  } else if (err instanceof SMSProviderError) {
    // Adapter call failed; `err.cause` has the original SDK error
  }
}

Delivery-status webhooks

Enable provider webhooks to keep sms-logs rows in sync with real delivery state. With webhooks: { enabled: true }, the Twilio/Telnyx/Plivo adapters are also handed a per-message delivery-status callback URL automatically — derived from config.serverURL + the webhook base path (e.g. https://app.com/api/sms/webhooks/twilio). No Messaging-Service or provider-portal step is required for a plain sender. (Vonage and AWS SNS have no per-message callback and are unaffected.)

import { smsPlugin } from '@elghaied/payload-plugin-sms'
import { twilioAdapter } from '@elghaied/payload-plugin-sms/twilio'

export default buildConfig({
  // ...
  plugins: [
    smsPlugin({
      adapter: twilioAdapter({
        accountSid: process.env.TWILIO_ACCOUNT_SID!,
        authToken: process.env.TWILIO_AUTH_TOKEN!,
        defaultFrom: process.env.TWILIO_FROM,
        webhook: { trustProxy: true }, // optional, if behind a proxy
      }),
      collections: { logs: { statusHistory: true } },
      webhooks: { enabled: true },
      onStatus: ({ event, log }) => {
        // optional: notify your app on every status transition
      },
    }),
  ],
})

Webhook URLs (Payload prepends /api):

ProviderURLRequired adapter webhook opts
Twilio/api/sms/webhooks/twilio(none — uses authToken)
Telnyx/api/sms/webhooks/telnyxpublicKey (Ed25519 PEM, from Telnyx portal)
Plivo/api/sms/webhooks/plivo(none — uses authToken)
Vonage/api/sms/webhooks/vonagesignatureSecret, signatureMethod: 'sha256hash' | 'sha512hash'
AWS SNS/api/sms/webhooks/aws-sns(none — verified via SigningCertURL; auto-confirms SubscriptionConfirmation)

Notes:

  • The auto-derived callback URL is skipped when serverURL is missing or points at localhost/127.0.0.1 (dev). Override it with webhooks.statusCallbackUrl (applies to Twilio/Telnyx/Plivo).
  • The callback URL handed to the provider must match the URL the receiver reconstructs for signature verification. Behind a reverse proxy, set the adapter's webhook: { trustProxy: true } so the host/protocol are read from forwarded headers — or use the webhooks.statusCallbackUrl override to pin both ends explicitly.
  • Signature verification is on by default. Set webhooks.verifySignature: false only for local testing.
  • Status updates are gated by rank (queued → sent → delivered, with failed terminal), so out-of-order or duplicate webhooks are dropped silently.
  • Set collections.logs.statusHistory: true to keep an append-only history of every event.
  • Vonage plain MD5 signing is not supported (insecure). Use sha256hash or sha512hash.
  • Twilio and Plivo do not sign timestamps — those providers cannot prevent replay attacks at the signature layer.

Internationalization

The sms-logs collection (labels, field labels, status options) and the dashboard widget ship with bundled en and fr translations, deep-merged into config.i18n.translations under an sms namespace. Your existing translations always win on conflict.

Override any string — or add a language — via i18n.translations.{lang}.sms:

buildConfig({
  i18n: {
    translations: {
      fr: { sms: { fieldTo: 'Destinataire' } },
      // add a new language by supplying its sms.* keys
    },
  },
  // ...
})

The raw translation tables are also available directly via the @elghaied/payload-plugin-sms/translations export.

Roadmap

  • Bulk / batch send
  • Templating (variable substitution, localization)
  • Per-recipient rate limiting
  • Inbound SMS handling
  • Vonage Messages API (JWT, MMS, WhatsApp)
  • MessageBird/Bird, Sinch, Infobip adapters

PRs welcome.

Compatibility

  • Payload ^3.0.0 (tested against 3.84.1)
  • Next.js ^16.0.0
  • Node ^18.20.2 || >=20.9.0
  • React 19 is an optional peer dependency — required only if you use the dashboard widget (@elghaied/payload-plugin-sms/rsc).

License

MIT

Similar plugins