Send SMS and OTP codes from Node.js

Send SMS from Node.js with the built-in fetch, and send and check one-time codes securely.

This guide sends SMS from a Node.js application with Fortwave, and uses it to send one-time passwords (OTP). It uses Node's built-in fetch and crypto, so there is no package to install.

What you need

Set your key

Read the key and sender ID from the environment. Never put the key in code you commit or ship to a browser.

.env
FORTWAVE_API_KEY=your-api-key
FORTWAVE_SENDER=MyApp

Send an SMS

POST /v1/sms sends one message: phone_number with + and the country code, your approved sender ID (up to 11 letters and digits), and a message of up to 600 characters.

fortwave.js
// fortwave.js
const FORTWAVE_SMS_URL = 'https://rest.api.fortwave.io/v1/sms'

/** Send one SMS; resolves to Fortwave's response with the message id and credits. */
export async function sendSms(phoneNumber, message) {
  const response = await fetch(FORTWAVE_SMS_URL, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.FORTWAVE_API_KEY}`,
      'Content-Type': 'application/json',
      Accept: 'application/json',
    },
    body: JSON.stringify({
      phone_number: phoneNumber,
      sender: process.env.FORTWAVE_SENDER,
      message,
    }),
    signal: AbortSignal.timeout(10_000),
  })

  const body = await response.json()
  if (!response.ok) {
    throw new Error(`Fortwave ${response.status}: ${body.message}`)
  }
  return body
}

A successful call returns the message's id, which delivery webhooks use too, with the credits it used (item_count) and the credits left (remaining_items):

Response
{
  "id": "01JCX4Q8V6M2R7T9K3N5P1W0YZ",
  "item_count": 1,
  "remaining_items": 4999,
  "status": "queued",
  "to": "+25761000000",
  "sender": "MyApp",
  "message": "Message queued for sending"
}

Send and check OTP codes

Your application generates the code; Fortwave delivers it, in under a second on average in Burundi. randomInt is cryptographically secure, only a hash of the code is stored, and timingSafeEqual compares it without leaking timing. store is any key-value store you already use, such as Redis or a database table.

otp.js
// otp.js
import { createHash, randomInt, timingSafeEqual } from 'node:crypto'
import { sendSms } from './fortwave.js'

const TEN_MINUTES = 10 * 60 * 1000
const hash = (code) => createHash('sha256').update(code).digest()

/** Generate a code, keep only its hash, and send it by SMS. */
export async function sendOtp(store, userId, phoneNumber) {
  const code = String(randomInt(100000, 1000000))
  await store.set(`otp:${userId}`, { hash: hash(code), expiresAt: Date.now() + TEN_MINUTES })
  await sendSms(phoneNumber, `Your verification code is ${code}. It expires in 10 minutes.`)
}

/** True once, for the right code before it expires. */
export async function verifyOtp(store, userId, code) {
  const entry = await store.get(`otp:${userId}`)
  if (!entry || entry.expiresAt < Date.now()) return false

  const matches = timingSafeEqual(entry.hash, hash(String(code)))
  if (matches) await store.delete(`otp:${userId}`)
  return matches
}

Handle errors

  • 401: the API key is missing, mistyped or revoked.
  • 400: the request cannot be sent, for example insufficient credits or a sender ID that is not approved. message explains why.
  • 422: a field is invalid, such as a phone number for the wrong country. errors lists each field.
  • 429: more than 500 sends in a minute from one key. Retry after a short wait.

Next steps

Still need help?

Our team answers Monday to Friday, during business hours (CAT).