SMSTunnel for Payload
Texts from your Payload hooks, endpoints and jobs, sent by your own phone
A plugin and three helpers, on the server
Payload hands each text to your SMSTunnel account, and your own Android phone sends it from its own SIM, so people see a number they know and can reply to. No SMS provider account and no sender registration: the phone runs the SMSTunnel app and is linked to your account. You can cut your app off at any time by deleting its API key in your dashboard.
What it does
- sendText()
- One text to one number, up to 1600 characters, from a collection hook, a custom endpoint or a job.
- sendCode()
- A sign-in or verification code of 4 to 10 digits, on its own allowance.
- The Jobs Queue
- Queue the text so saves don't wait for SMSTunnel; a retried job can't text twice.
- Nothing in the admin
- No collections, fields or endpoints. The settings stay in config.custom, which Payload never sends to the admin panel.
- Safe retries
- An idempotencyKey per text: a second call with the same key within 24 hours never sends a second text.
- Requirements
- Payload 3 (tested with 3.92.1), server side only. No other dependencies.
1. Install
npm install @narcisbodea/smstunnel-payload Payload 3 (tested with 3.92.1), server side only. No other dependencies.
2. Get your key
- 1. Install the SMSTunnel app from Google Play on your Android phone and sign in.
- 2. In your dashboard, open Apps → Add an app, pick Node.js, name it (for example "My Payload app") and click Create the key.
- 3. Copy the key right away: it's shown only once. You can stop or delete the app there anytime, and My Payload app can't send texts anymore.
Get the steps with your key in them
It opens Add an app with Node.js picked. Once the key is made, the dashboard shows every step and command with the key already filled in, ready to copy.
Put it in your environment (.env, or your host's secret settings), never in your code:
SMSTUNNEL_API_KEY=sk_live_... 3. Add the plugin
Add it to payload.config.ts:
import { buildConfig } from 'payload'
import { smsTunnelPlugin } from '@narcisbodea/smstunnel-payload'
export default buildConfig({
// ...
plugins: [smsTunnelPlugin()],
})
It adds no collections, fields or endpoints. It keeps its settings in config.custom, which
Payload never sends to the admin panel, and warns at start-up when there is no key.
- apiKey
- Default process.env.SMSTUNNEL_API_KEY.
- deviceId
- The phone that sends, when your account has several (its ID is under Phones, with a Copy button). Default process.env.SMSTUNNEL_DEVICE_ID, else your phone that is online.
- defaultCountryCode
- Completes numbers written without + or 00, e.g. '+40'. It wins over the phone's own country.
- baseUrl
- Default process.env.SMSTUNNEL_BASE_URL, else https://smstunnel.io.
- timeoutMs
- Default 30000.
- enabled
- false turns sending off, for example in development: the helpers then throw without calling SMSTunnel. Default true.
4. Text the customer when an order is created (a hook)
import type { CollectionConfig } from 'payload'
import { sendText } from '@narcisbodea/smstunnel-payload'
export const Orders: CollectionConfig = {
slug: 'orders',
fields: [
{ name: 'customerName', type: 'text' },
{ name: 'phone', type: 'text' },
],
hooks: {
afterChange: [
async ({ doc, operation, req }) => {
// Text the customer once, when the order is created, from your own phone.
if (operation !== 'create' || !doc.phone) return doc
try {
await sendText(req.payload, {
to: doc.phone,
message: `Thanks ${doc.customerName ?? ''}! We got your order #${doc.id}.`,
// The id and the creation time keep the key unique, so a retry can't send a second text.
idempotencyKey: `order-${doc.id}-${doc.createdAt}`,
})
} catch (error) {
// A text that can't go out must not fail the save: log it.
req.payload.logger.error(`SMSTunnel: ${(error as Error).message}`)
}
return doc
},
],
},
} The hook waits for SMSTunnel's answer, usually well under a second. To keep saves from waiting at all, queue the text instead (below).
Ask for numbers in the international format (+14155550123), or set
defaultCountryCode. Keep the phone field a text field: a number loses the
+ and leading zeros, and the plugin refuses a JavaScript number.
Queue the text (Payload's Jobs Queue)
Registered with jobs: { tasks: [textCustomer] } in payload.config.ts:
import type { TaskConfig } from 'payload'
import { sendText } from '@narcisbodea/smstunnel-payload'
// A queued text: saves don't wait for SMSTunnel. A retry of the job reuses its key, so it can't text twice;
// the creation time keeps the key unique even if job ids start over (a new database).
export const textCustomer: TaskConfig<{ input: { to: string; message: string }; output: { messageId: string } }> = {
slug: 'textCustomer',
inputSchema: [
{ name: 'to', type: 'text', required: true },
{ name: 'message', type: 'text', required: true },
],
outputSchema: [{ name: 'messageId', type: 'text', required: true }],
retries: 2,
handler: async ({ input, job, req }) => {
const sent = await sendText(req.payload, { to: input.to, message: input.message, idempotencyKey: `job-${job.id}-${job.createdAt}` })
return { output: { messageId: sent.messageId } }
},
} Then, from a hook or an endpoint:
await req.payload.jobs.queue({ task: 'textCustomer', input: { to: doc.phone, message: '…' } }) Jobs run when your app runs them (autoRun or a cron).
The helpers
All of them take req.payload (or the result of getPayload()), send one
text to one number, and return { messageId, queued, replayed }:
- sendText(payload, { to, message, deviceId?, defaultCountryCode?, idempotencyKey? })
- A text, up to 1600 characters. For several people, call it once per number.
- sendCode(payload, { to, message, ... })
- A sign-in or verification code. The text must contain the code: 4 to 10 digits on their own (482913, or 123-456), 320 characters at most. It counts against your sign-in code allowance.
- getSmsTunnel(payload)
- The client, for getStatus(messageId), listPhones(), getUsage().
idempotencyKey: a second call with the same key within 24 hours gets the first answer back
(replayed: true) instead of a second text. Use one key per text.
When a text doesn't go out
The helpers throw an SmsTunnelError with status,
code, retryAfter and mayHaveSent:
- 401
- The API key is wrong, deactivated or deleted. Create a new one under Apps → Add an app.
- 403
- The key lacks a permission (code: 'PERMISSION_REQUIRED', with permission), or your plan doesn't include what was asked.
- 429
- Too many requests (30 sends a minute per key): retryAfter says how many seconds to wait. Without it, today's allowance of your plan is used up.
- 5xx, or no answer
- SMSTunnel had a problem. mayHaveSent is true: check the Messages page in your dashboard before you send it again, or send it again with the same idempotencyKey.
- 400
- SMSTunnel refused a field, such as a number it can't read or a code text without a code.
- 422
- The idempotency key was already used for a different text in the last 24 hours.
A number that isn't one, several numbers in to, an empty text or one over 1600 characters is
refused before anything is sent (kind: 'input'), and so is a call without a key or without the
plugin. If your phone is offline, the text isn't lost: queued is true, it
waits in the queue on your account and goes out as soon as the phone is back online (up to 3 days). The helpers never
resend a text by themselves.
Limits worth knowing
- 30 send requests a minute per key. Over it, an
SmsTunnelErrorwithretryAfter. - Plans: each plan has its own allowance. See Pricing.
- Length: up to 1600 characters; sign-in codes up to 320.
- Numbers: use the international format (
+14155550123), or setdefaultCountryCode. - Offline phone: the text waits on your account and goes out when the phone is back online, for up to 3 days.
Build it with an AI assistant
Copy this prompt into Claude, ChatGPT, Cursor or Copilot and replace the part in [brackets]. Don't paste your API key into the chat: the prompt doesn't need it.
Help me send texts from my Payload CMS 3 app with SMSTunnel.
About SMSTunnel (https://smstunnel.io): my own apps and tools hand text messages (SMS) to my SMSTunnel account, and my own Android phone sends them from my own number, on my own SIM and plan. The phone runs the SMSTunnel app from Google Play (https://play.google.com/store/apps/details?id=io.smstunnel.app), signed in to my account.
What I want: [describe what should send a text, to whom, and when]
How it works:
- Use @narcisbodea/smstunnel-payload (npm install @narcisbodea/smstunnel-payload; Payload 3, server side only, no other dependencies) and add smsTunnelPlugin() to plugins in payload.config.ts (options: apiKey, default process.env.SMSTUNNEL_API_KEY; deviceId, which phone sends; defaultCountryCode, e.g. "+40"; baseUrl; timeoutMs; enabled). It adds no collections, fields or endpoints and keeps its settings in config.custom, which Payload never sends to the admin panel.
- Server-side helpers, from '@narcisbodea/smstunnel-payload': sendText(req.payload, { to, message, deviceId?, defaultCountryCode?, idempotencyKey? }) → { messageId, queued, replayed }: one text to one number, up to 1600 characters; sendCode(req.payload, { to, message }) for sign-in codes: the text must contain a code of 4 to 10 digits standing on its own (e.g. 482913 or 123-456), at most 320 characters; getSmsTunnel(req.payload) → client with getStatus(messageId), listPhones(), getUsage().
- They throw SmsTunnelError with status, code, retryAfter and mayHaveSent. Use them in collection hooks (afterChange with operation === 'create'), custom endpoints, or a Jobs Queue task (pass idempotencyKey: `job-${job.id}-${job.createdAt}` so retries can't text twice). The helpers never resend by themselves.
- Errors: 401 wrong key, 403 missing permission or plan (code such as PERMISSION_REQUIRED), 429 too many requests (Retry-After) or today's allowance used up, 5xx SMSTunnel problem (mayHaveSent: the text may have gone out: never resend without the same idempotencyKey), 422 an idempotency key already used for a different text. If the phone is offline, the text waits in the queue (queued: true) and goes out when the phone is back online.
- 30 send requests a minute per key; defaultCountryCode completes numbers written without + or 00. Keep phone fields of type text: a number loses the + and leading zeros.
- The API key comes from my SMSTunnel dashboard (https://dashboard.smstunnel.io): Apps → Add an app → Create the key. It is shown only once and can send texts and check whether they went out.
Rules for your answer:
- Keep the API key in an environment variable or the platform's secret store (for example SMSTUNNEL_API_KEY). Never put it in source code, in a repository, or in code that runs in a browser or a mobile app: call SMSTunnel from a server. I will not paste my key in this chat; use a placeholder.
- Validate phone numbers before sending (international format, like +14155550123) and skip or report the invalid ones.
- Handle errors: log or show what went wrong, retry only after 429, 5xx or network errors and only a few times, and never send the same text twice.
- Only send texts people expect from me: alerts to myself, reminders, sign-in codes, updates they asked for. No unsolicited texts. Responsible use
Built for alerts to yourself and your team, and texts people expect from you. One text goes to one number. Sending unsolicited messages from a consumer SIM generally breaches mobile carrier terms of service.
Payload is a trademark of its owner. SMSTunnel is a third-party integration and is not affiliated with, endorsed by, or sponsored by Payload (payloadcms.com).