
Add SMS Account Recovery to Your Node.js App (Lessons From Google's Lockout Fix)
When your app locks a user out, let them back in with a code by text. Build SMS account recovery in Express: hashed codes, expiry, attempt limits and rate limits.
When your app locks a user out, give them a fast way back in that does not need your support team. Send a 6-digit code by SMS to the phone number on the account. Check the code on a verify endpoint. Then unlock the account or give out a short-lived password reset token. This tutorial builds that flow in Node.js and Express in about 150 lines, with textbee sending the text from your own Android phone.
We ran every step on 3 December 2026 with Node 24 and Express 5.3.0, against a local mock of the textbee API. The curl output below is from that run.
TL;DR
- Google just made this move. After a wrongly disabled account went viral, Google said it will use SMS verification more often so people can fix false lockouts themselves.
- The code:
crypto.randomIntmakes 6 digits. Store only an HMAC of the code, an expiry (10 minutes) and an attempt counter (5 tries). Delete the code after one successful use. - The send: one
fetchcall toPOST /api/v1/gateway/send-smswith anx-api-keyheader. - The guards: 1 text per minute and 5 per day per phone number, a per-IP limit on both endpoints,
crypto.timingSafeEqualfor the check, and the same answer for every email address. - The limits: SMS codes can be stolen through a SIM swap. For high-value accounts, add a second check. See SMS OTP vs email OTP vs TOTP.
- The cost: textbee Free covers 300 messages a month. Pro is $14.99 a month for up to 5,000.
What happened with the Google account lockout?
On the weekend of 28 November 2026, a Railway support engineer posted on X that Google had disabled his Google account. The post passed 5 million views, and Google restored the account within about a day (Windows Latest, Daily Caller). Google said on X: "This was a mistake on our part, and has nothing to do with AI usage." CEO Sundar Pichai said automated account security signals caused the lockout. He added: "Starting tomorrow, we're expanding the usage of SMS verification in situations like this, so more people can address issues like this in seconds, without waiting on us." (Nation Press, Daily Caller, checked December 2026.)
The lesson for your own app: automated fraud checks flag real users sometimes. A user who is locked out needs a way back in that takes seconds, not a support ticket.
Why use SMS for account recovery?
- It works on any phone. The user needs no app and no data connection. A basic phone gets the code.
- You already have the number. Many apps collect a phone number at sign-up or for 2FA.
- It is a different channel. A user who lost a password, or whose session was flagged, still has their phone.
SMS is a fallback, not the strongest factor. The section How safe is SMS account recovery? covers the limits.
Before you start
- Node.js 20 or later. It has
fetchbuilt in. - Express:
npm install express. We used Express 5.3.0. - The textbee app on an Android phone: download it and follow the quickstart.
- An API key from the textbee dashboard. See API keys.
- A server secret for hashing codes. Make one with
openssl rand -hex 32.
Put the values in the environment:
export TEXTBEE_API_KEY=your-api-key
export RECOVERY_SECRET=$(openssl rand -hex 32)The app has four files: textbee.js sends the text, recovery.js handles codes, rate-limit.js counts requests and app.js has the routes. Set "type": "module" in package.json.
Step 1: Send a text with textbee
textbee.js posts the recipient and the message to textbee. textbee pushes the message to your phone, and the phone sends it through its SIM.
// textbee.js: send one SMS through your Android phone (Node 20+ has fetch built in).
const TEXTBEE_URL = process.env.TEXTBEE_URL ?? 'https://api.textbee.dev/api/v1'
export async function sendSms(to, message) {
const response = await fetch(`${TEXTBEE_URL}/gateway/send-sms`, {
method: 'POST',
headers: {
'x-api-key': process.env.TEXTBEE_API_KEY,
'Content-Type': 'application/json',
},
body: JSON.stringify({ recipients: [to], message }),
})
if (!response.ok) {
throw new Error(`textbee returned ${response.status}: ${await response.text()}`)
}
const { data } = await response.json()
return data.smsBatchId
}TEXTBEE_URL lets the tests point at a local mock. It also works for a self-hosted textbee server.
A 200 response means textbee accepted the text, not that the phone delivered it. The errors to expect: 400 when no device is enabled, 401 for a wrong API key and 429 when your plan limit is used up. See send an SMS with the API.
Step 2: Create, store and check the code
recovery.js makes the code and keeps only its hash:
// recovery.js: create, store and check one-time recovery codes.
import crypto from 'node:crypto'
const SECRET = process.env.RECOVERY_SECRET // 32+ random bytes, kept on the server only
if (!SECRET) throw new Error('Set RECOVERY_SECRET')
const CODE_TTL_MS = Number(process.env.CODE_TTL_MS ?? 10 * 60 * 1000) // 10 minutes
const MAX_ATTEMPTS = 5
// userId -> { hash, expiresAt, attempts }. Use Redis or a DB table in production.
const codes = new Map()
function hashCode(userId, code) {
return crypto.createHmac('sha256', SECRET).update(`${userId}:${code}`).digest()
}
export function createCode(userId) {
const code = crypto.randomInt(0, 1_000_000).toString().padStart(6, '0')
// A new code replaces any older one, so only one code works at a time.
codes.set(userId, {
hash: hashCode(userId, code),
expiresAt: Date.now() + CODE_TTL_MS,
attempts: 0,
})
return code
}
export function checkCode(userId, code) {
const entry = codes.get(userId)
if (!entry) return false
if (Date.now() > entry.expiresAt || entry.attempts >= MAX_ATTEMPTS) {
codes.delete(userId)
return false
}
entry.attempts += 1 // count the attempt before the comparison
const given = hashCode(userId, String(code))
if (!crypto.timingSafeEqual(given, entry.hash)) return false
codes.delete(userId) // single use
return true
}Why each part is there:
crypto.randomIntuses a secure random source.Math.randomdoes not.padStartkeeps codes such as004217at 6 digits.- An HMAC, not the code. A leaked store or log shows no usable codes. A 6-digit code has only 1,000,000 values, so a plain SHA-256 is easy to reverse. The HMAC needs
RECOVERY_SECRET, which stays out of the database. The user id is part of the input, so a hash does not match for another user. - 10 minutes and 6 digits match NIST SP 800-63B-4. It says issued recovery codes "SHALL include at least six decimal digits" and are valid for at most "10 minutes when sent via text message or voice" (NIST SP 800-63B-4, section on issued recovery codes, checked December 2026).
- 5 attempts. The counter goes up before the comparison, so parallel guesses also count. After 5 misses the code is dead, and the user asks for a new one.
crypto.timingSafeEqualtakes the same time whether the first byte or the last byte differs. Both inputs are 32-byte HMAC digests, so the lengths always match.- Single use. A correct code is deleted at once.
Step 3: Add rate limits
rate-limit.js is a fixed-window counter:
// rate-limit.js: fixed-window counters. Use Redis INCR + EXPIRE in production.
const hits = new Map() // key -> { count, resetAt }
export function allow(key, limit, windowMs) {
const now = Date.now()
const entry = hits.get(key)
if (!entry || now >= entry.resetAt) {
hits.set(key, { count: 1, resetAt: now + windowMs })
return true
}
if (entry.count >= limit) return false
entry.count += 1
return true
}The routes use four limits:
| Key | Limit | Stops |
|---|---|---|
| Per IP, request a code | 10 per 15 minutes | One client asking for codes for many accounts |
| Per phone number | 1 per minute | Repeat taps and text floods to one person |
| Per phone number | 5 per day | Slow guessing over many codes |
| Per IP, verify a code | 20 per 15 minutes | One client guessing codes |
With 5 codes a day and 5 tries per code, an attacker gets 25 guesses a day out of 1,000,000 values. That is a 1 in 40,000 chance per day for one account.
Step 4: Add the request endpoint
POST /recover/start takes an email and texts a code to the phone number on that account:
app.post('/recover/start', (req, res) => {
if (!allow(`start:ip:${req.ip}`, 10, 15 * MINUTE)) {
return res.status(429).json({ error: 'Too many requests. Try again later.' })
}
const user = users.get(String(req.body?.email ?? '').toLowerCase())
// Same answer for every email, so the endpoint does not reveal accounts.
res.status(202).json(SENT)
if (!user?.phone) return
if (!allow(`start:phone:${user.phone}`, 1, MINUTE)) return
if (!allow(`start:phone-day:${user.phone}`, 5, DAY)) return
const code = createCode(user.id)
const text = `Your Acme recovery code is ${code}. It expires in 10 minutes. If you did not ask for it, ignore this text.`
sendSms(user.phone, text).catch((err) => console.error('recovery SMS failed:', err.message))
})Three choices protect your users:
- One answer for all. A known email, an unknown email and a rate-limited number all get the same 202 response: "If the account exists, we sent a code to its phone number." Nobody can use the form to find out who has an account.
- Send after the response. The route answers first and sends the text after. An existing account does not make the response slower, so timing does not reveal accounts either.
- Only the number on file. The code goes to the phone number stored on the account, never to a number from the request. An attacker cannot send your texts to their own numbers.
The text says who sent it, how long the code works and what to do if the user did not ask for it.
Step 5: Add the verify endpoint
POST /recover/verify checks the code, unlocks the account and returns a reset token. POST /recover/reset uses the token once. It is a stub: add your password update where the comment says:
app.post('/recover/verify', (req, res) => {
if (!allow(`verify:ip:${req.ip}`, 20, 15 * MINUTE)) {
return res.status(429).json({ error: 'Too many requests. Try again later.' })
}
const user = users.get(String(req.body?.email ?? '').toLowerCase())
const code = String(req.body?.code ?? '')
if (!user || !/^\d{6}$/.test(code) || !checkCode(user.id, code)) {
return res.status(400).json(INVALID)
}
user.locked = false
const token = crypto.randomBytes(32).toString('base64url')
const tokenHash = crypto.createHash('sha256').update(token).digest('hex')
resetTokens.set(tokenHash, { userId: user.id, expiresAt: Date.now() + 15 * MINUTE })
res.json({ unlocked: true, resetToken: token, expiresIn: 900 })
})
app.post('/recover/reset', (req, res) => {
const tokenHash = crypto.createHash('sha256').update(String(req.body?.resetToken ?? '')).digest('hex')
const entry = resetTokens.get(tokenHash)
resetTokens.delete(tokenHash) // single use
if (!entry || Date.now() > entry.expiresAt) {
return res.status(400).json({ error: 'Invalid or expired reset token.' })
}
// Hash and save req.body.newPassword for entry.userId here, then end old sessions.
res.json({ passwordReset: true })
})A wrong code, an expired code, a used code and an unknown email all get the same answer: "Invalid or expired code." The reset token is 32 random bytes and works once for 15 minutes. The server stores only its SHA-256 hash. A plain SHA-256 is enough here because the token has 256 bits of randomness.
Pick what a correct code does for your app:
- Fraud flag on a real user: clear the flag (
user.locked = false) and sign them in. - Lost password: return the reset token and let the user set a new password.
- New device: trust the device and sign in.
The rest of app.js sets up Express and the demo user store:
// app.js: SMS account recovery for an Express app.
import crypto from 'node:crypto'
import express from 'express'
import { sendSms } from './textbee.js'
import { createCode, checkCode } from './recovery.js'
import { allow } from './rate-limit.js'
const MINUTE = 60 * 1000
const DAY = 24 * 60 * MINUTE
// Demo user store. Your app reads this from its database.
const users = new Map([
['[email protected]', { id: 'u_1', phone: '+15555550123', locked: true }],
])
const resetTokens = new Map() // sha256(token) -> { userId, expiresAt }
const app = express()
app.set('trust proxy', 1) // behind one proxy, so req.ip is the client address
app.use(express.json())
const SENT = { message: 'If the account exists, we sent a code to its phone number.' }
const INVALID = { error: 'Invalid or expired code.' }
// ... the three routes from steps 4 and 5 ...
app.listen(3000, () => console.log('Acme listening on http://localhost:3000'))Set trust proxy to match your setup. Without it behind a proxy, every request has the proxy's IP address, and the per-IP limits block everyone at once. If no proxy sits in front of the app, remove the line. Otherwise any client can set X-Forwarded-For and pick its own IP address, which skips the per-IP limits.
Step 6: Test it with curl and a mock textbee server
The mock stands in for the textbee API. It records each send and returns the same 200 body as textbee. GET /last shows the last text, so the test can read the code:
// mock-textbee.js: a local stand-in for the textbee API. It records each send.
import http from 'node:http'
let last = null
http
.createServer((req, res) => {
let body = ''
req.on('data', (chunk) => (body += chunk))
req.on('end', () => {
if (req.method === 'POST' && req.url === '/api/v1/gateway/send-sms') {
last = { apiKey: req.headers['x-api-key'], ...JSON.parse(body) }
console.log('send-sms', JSON.stringify(last))
res.writeHead(200, { 'Content-Type': 'application/json' })
return res.end(JSON.stringify({
data: {
success: true,
message: 'SMS added to queue for processing',
smsBatchId: 'mock-batch-1',
recipientCount: last.recipients.length,
},
}))
}
if (req.method === 'GET' && req.url === '/last') {
res.writeHead(200, { 'Content-Type': 'application/json' })
return res.end(JSON.stringify(last))
}
res.writeHead(404).end()
})
})
.listen(4000, () => console.log('mock textbee on http://localhost:4000'))Start both servers:
node mock-textbee.js &
TEXTBEE_URL=http://localhost:4000/api/v1 TEXTBEE_API_KEY=test-key \
RECOVERY_SECRET=$(openssl rand -hex 32) node app.js &Request a code
curl -s -X POST localhost:3000/recover/start \
-H 'Content-Type: application/json' -d '{"email":"[email protected]"}'
# {"message":"If the account exists, we sent a code to its phone number."}
curl -s localhost:4000/last
# {"apiKey":"test-key","recipients":["+15555550123"],"message":"Your Acme recovery code is 307022. It expires in 10 minutes. If you did not ask for it, ignore this text."}An unknown email gets the same 202 answer and sends no text. A second request for Ada within 60 seconds also gets the same answer, and the mock recorded no second send.
Try a wrong code, then the right one
curl -s -X POST localhost:3000/recover/verify \
-H 'Content-Type: application/json' -d '{"email":"[email protected]","code":"000000"}'
# {"error":"Invalid or expired code."} (400)
curl -s -X POST localhost:3000/recover/verify \
-H 'Content-Type: application/json' -d '{"email":"[email protected]","code":"307022"}'
# {"unlocked":true,"resetToken":"-lUAz0Ja5BxJnn6bqUhi1GigLeA3BWzolr7KV7l-aBQ","expiresIn":900} (200)The same code a second time returns {"error":"Invalid or expired code."} with a 400, because the code was single use. The reset token works once ({"passwordReset":true}), and the second try gets {"error":"Invalid or expired reset token."}.
Test an expired code
To test expiry without a 10-minute wait, we started the app with CODE_TTL_MS=3000, asked for a code and waited 4 seconds:
curl -s -X POST localhost:3000/recover/verify \
-H 'Content-Type: application/json' -d '{"email":"[email protected]","code":"614442"}'
# {"error":"Invalid or expired code."} (400)Test the attempt and IP limits
After 5 wrong codes, the right code also fails with {"error":"Invalid or expired code."}. The user must ask for a new code. When one IP address asked for codes more than 10 times in 15 minutes, the next request got a 429: {"error":"Too many requests. Try again later."}.
How do I move this to production?
The Map stores live in one process and are lost on restart. Replace them before you ship:
- Redis: store each code as a hash under
recovery:<userId>withHSET, set a 10-minute expiry withPEXPIRE, and useHINCRBYfor the attempt counter. UseINCRandEXPIREfor the rate limits. All app servers then share the same counters. - A database table: columns
user_id(unique),code_hash,expires_at,attemptsandcreated_at. Run the attempt increment and the check in one transaction. Delete expired rows on a schedule.
Also add these:
- Tell the user. Send an email or a second text when a recovery succeeds. NIST SP 800-63B-4 says account recovery "SHALL cause a notification to be sent to the subscriber" (NIST, checked December 2026).
- End old sessions after a password reset.
- Log each step (request, send, wrong code, success) with the user id, without the code.
- Follow delivery. A 200 from textbee means the text is queued. Use the
smsBatchIdwith delivery status or a webhook if you want to show "text sent" in your UI.
How safe is SMS account recovery?
Safe enough for most apps, with clear limits:
- SIM swap. An attacker who convinces a carrier to move the user's number to a new SIM gets the code. NIST says the use of the phone network for out-of-band codes "is restricted" and lists "SIM change" and "number porting" as risk signals (NIST SP 800-63B-4, checked December 2026).
- The code can be phished. A user can type the code into a fake site. The text tells users to ignore codes they did not ask for, but some users still give them away.
For high-value accounts (money, admin rights, health data), do not let one SMS code give full access. Ask for a second check too, such as an email link, a TOTP code or a passkey, or add a waiting period before a password change. For the trade-offs of each method, read SMS OTP vs email OTP vs TOTP.
Frequently asked questions
Is SMS recovery safe enough?
For most consumer and SaaS apps, yes, with the limits in this post: hashed codes, 10-minute expiry, 5 tries and rate limits. SIM swap and phishing are real risks. For accounts with money or admin rights, pair SMS with a second factor.
What if the user changed their phone number?
SMS recovery cannot help then. Offer another path, such as an email link or a support review. Let signed-in users update their number, and confirm the new number with a code before you save it. Send a notice to the email on file when the number changes.
Can I use the user's local number format?
Yes. textbee sends to any number your phone could text. A local number works when it is in the same country as the SIM that sends. Use the international format (+15555550123) to reach a number in another country. If your users live in many countries, store numbers in international format at sign-up. See phone number format.
What does it cost?
Each recovery text is one message on your textbee plan. Free covers 300 messages a month (50 a day). Pro is $14.99 a month for up to 5,000 messages, and Scale is $29.99 a month for up to 25,000. The texts go out on your SIM plan, so there is no per-message fee from textbee. See pricing.
Why does the request endpoint answer 202 for unknown emails?
So that the form does not tell anyone which emails have accounts. The user who owns the account gets the text. Everyone else sees the same message.
Can I use this for login codes too?
Yes. The same createCode and checkCode functions work for sign-in and 2FA codes. For a Supabase project, see Supabase phone login with textbee.
Keep going
- Send SMS from Node.js: the send call, errors and retries
- Set up 2FA with textbee
- API reference: send, receive, webhooks and devices
Download textbee and send your first recovery code from your own phone.
Get more textbee in Google Search
Add textbee.dev as a preferred source. Our posts show up more often in your Google results.
You may also like

SMS OTP vs Email OTP vs TOTP in 2026: Which 2FA Should You Build?
Compare SMS OTP, email OTP, TOTP (authenticator apps), and hardware keys for 2FA in 2026: security, UX, cost, and implementation. Includes a textbee OTP code example.

Supabase Phone Login With Your Own Number: The Send SMS Hook
Send Supabase phone login codes from your own Android number. A Send SMS Hook calls an Edge Function that checks the signature and passes the OTP to textbee.

Send Text Messages from Node.js: SMS API Tutorial with Your Android Phone
Send real SMS messages from Node.js using your Android phone as the gateway. One async function, your own phone number, zero per-message fees.