100MB FREEResidential proxiesClaim
NumberOTP

SMS OTP Webhook in Node.js: Verify, Dedupe, Test

Build an SMS OTP webhook in Node.js: verify the HMAC signature on the raw body, skip duplicate events, test locally, with measured results from a real run.

NNanami
November 20, 202612 min read

An SMS OTP webhook in Node.js lets the verification code come to your server the moment the SMS lands, instead of your code asking an API every few seconds. The receiver itself is short: read the raw request body, check the HMAC SHA-256 signature, skip events you have already handled, answer 200. Most broken receivers fail on the first two steps, and they fail in a way a quick test won't catch. This guide is the written companion to our SMS OTP webhook video, with the raw results of a local run on 21 November 2026.

We run NumberOTP, so the examples use our webhook format and the numberotp npm package (0.1.1). The signature and duplicate rules apply to any service that signs its webhooks with HMAC. Every API fact below comes from our API reference and webhook docs, read the same night.

How an SMS OTP webhook works

You buy a number with a webhook URL attached, your own app texts a code to it, and NumberOTP sends one POST request per SMS to that URL. There is no loop on your side and no connection held open while you wait.

  1. Your code creates an activation (one number, one service) and passes webhook_url, or relies on the global webhook set in the dashboard under Developer.
  2. You enter the number in the sign-up or login form you are testing. Your app sends its SMS.
  3. When the SMS arrives, a JSON body is POSTed to your URL with the code, the full message text, an event name and a unique event_id.
  4. Your receiver verifies the signature, records the event_id, hands the code to whatever is waiting for it, and answers 200.

The webhook URL must be a public HTTPS address. A per-activation webhook_url overrides the global one for that number only, which is handy when one test run should report to its own endpoint.

Step 1: buy a number with a webhook URL

With the Node SDK, the webhook URL is one extra field on the purchase. The client reads your API key from NOTP_API_KEY.

import { NumberOTP } from 'numberotp'

const notp = new NumberOTP() // reads NOTP_API_KEY

const n = await notp.activations.create({
  service: 'ot',
  country: '187',
  webhook_url: 'https://your-app.com/otp',
})
console.log('Use this number:', n.data.phoneNumber)

Service ot means "any other service" and country 187 is the United States in our country list. If your test also needs to normalise the number before typing it into a form, our guide to E.164 formatting mistakes in phone fields covers the usual traps.

What the payload looks like

Each POST carries one JSON object. This is the documented example, with the phone number masked:

{
  "id": "act_8f7d98x",
  "phone_number": "1•••••••••71",
  "service": "wa",
  "country": "187",
  "otp": "482910",
  "full_sms": "Your code is 482910 …",
  "status": "received",
  "event": "activation.code_received",
  "event_id": "evt_3f1c9a7e2b4d6f8a0c1e3b5d"
}

The event field tells you which SMS this is. It is activation.code_received for the first SMS on a number, activation.sms_received for each later one (for example after you ask the app to resend), and rental.sms_received on rented numbers. The docs say to use event_id to ignore duplicates.

Verify the webhook signature in Node.js

Verify every request before you trust it, because anyone who learns your URL can POST to it. NumberOTP signs the body with HMAC SHA-256 using your webhook secret and sends the result in the x-numberotp-signature header as sha256=<hex>.

Here is the full receiver, 16 lines of Express:

import express from 'express'
import { verifyWebhook } from 'numberotp'

const app = express(), seen = new Set()
const raw = express.raw({ type: '*/*' })
app.post('/otp', raw, async (req, res) => {
  const sig = req.get('x-numberotp-signature')
  const secret = process.env.NOTP_WEBHOOK_SECRET
  if (!(await verifyWebhook(req.body, sig, secret)))
    return res.sendStatus(401)
  const e = JSON.parse(req.body)
  if (!seen.has(e.event_id)) console.log(e.event, e.otp)
  seen.add(e.event_id)
  res.sendStatus(200)
})
app.listen(3000)

Three details matter more than they look:

  • express.raw() on this route, not express.json(). The HMAC covers the exact bytes that were sent. req.body must be a Buffer when you verify it. If your app registers app.use(express.json()) globally, mount the webhook route before it, because whichever parser runs first consumes the request stream.
  • Parse only after the check passes. JSON.parse(req.body) runs on the verified bytes.
  • verifyWebhook fails closed. In numberotp 0.1.1 it returns false when the header or secret is missing, or when the header is not 64 hex characters (with or without the sha256= prefix). Then it compares the digests without stopping at the first differing character.

Our other SDKs and the CLI are listed in the SDK guides for Node, Python, Go and PHP.

Why webhook signatures fail: a measured comparison

The common mistake is to parse the JSON first, then hash JSON.stringify(req.body). It passes a quick test, so it ships, and then rejects real requests later. To show exactly where it breaks, we ran both versions side by side on one laptop on 21 November 2026 (Node 26.9.0, Express 4.22.3, numberotp 0.1.1). Each request was signed with openssl using a throwaway test secret. No number was bought and nothing was charged.

The "parse then stringify" receiver looked like this, a pattern you will find in many copy-paste snippets:

app.post('/otp', express.json(), (req, res) => {
  const sig = req.get('x-numberotp-signature') || ''
  const hash = crypto.createHmac('sha256', process.env.NOTP_WEBHOOK_SECRET)
    .update(JSON.stringify(req.body)).digest('hex')
  const ok = crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(`sha256=${hash}`))
  res.sendStatus(ok ? 200 : 401)
})

Raw HTTP status codes from the run, every request signed correctly unless noted:

RequestRaw-body receiverParse-then-stringify receiver
Compact JSON, valid signature200200
Body with a literal UTF-8 character, valid signature200200
Same JSON, pretty-printed with spaces and newlines200401
Text with a — escape instead of the literal character200401
Header sha256=abc (too short)401500 (crash)
Code changed from 482910 to 000000 (tampered)401not run
No signature header401not run

What the table shows:

  • The broken version passes the easy cases. Compact JSON with literal characters re-serialises to the same bytes, so the hashes match and the bug stays hidden.
  • Any formatting difference breaks it. Whitespace and escaped characters disappear when the body is parsed and stringified again. The signature was valid both times, but the receiver answered 401 because it hashed different bytes. A sender only has to change its JSON formatting for every request to start failing.
  • A malformed header crashed the request. Node's crypto.timingSafeEqual throws when the two buffers differ in length (Node.js crypto documentation). The log showed RangeError: Input buffers must have the same byte length and Express returned 500. If you compare by hand, check the lengths first and treat a mismatch as invalid.

The raw-body receiver accepted every correctly signed variant and rejected the tampered, missing and malformed ones. That is the whole argument for express.raw().

Handle duplicate webhook events with event_id

Treat every webhook as "at least once": the same event can reach you twice, so record each event_id and skip one you have already handled. In the local run, sending the identical signed body a second time returned 200 both times, and the code was logged once.

  • Answer 200 even for a duplicate. The request was valid, you just have nothing new to do.
  • Store IDs in a database in production. A Set in memory is fine for a demo, but it is empty after a restart and not shared between instances. A unique index on event_id makes the check race-free when two copies arrive at once: the second insert fails and you treat it as a duplicate.
  • Respond fast, then do the slow work. Save the event and answer. Run anything heavy (database writes across services, notifications) after the response or in a queue. Shopify's developer docs give the same advice for their webhooks: verify the delivery, ignore duplicates and respond with 200 quickly.
  • Don't confuse duplicates with resends. A resent code is a new SMS with a new event_id and the event activation.sms_received. Use the latest code, not the first one you saw.

Test the webhook locally without a tunnel

You don't need a public URL to test the receiver itself: sign a sample body yourself, the way the sender does, and POST it to localhost. A tunnel only matters later, when real events have to reach your laptop.

SECRET=test_secret_for_this_demo
BODY='{"otp":"482910","event":"activation.code_received","event_id":"evt_demo_001"}'
SIG="sha256=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$SECRET" | awk '{print $NF}')"

curl -s -o /dev/null -w '%{http_code}\n' -X POST http://localhost:3000/otp \
  -H 'content-type: application/json' \
  -H "x-numberotp-signature: $SIG" --data-binary "$BODY"

Start the server with NOTP_WEBHOOK_SECRET=test_secret_for_this_demo node server.mjs, run the command, and you should see 200 and one log line. Then change one digit in BODY without re-signing (expect 401) and send the original again (expect 200 and no second log line). Use --data-binary, not -d: -d strips newlines from files, which changes the bytes you signed.

For full end-to-end tests where a browser fills in the form, our Playwright OTP fixture tutorial waits for the code over the API instead. Our broader guide on testing SMS OTP verification without your own phone covers where real numbers fit next to auth-provider test numbers.

Webhook vs long-poll vs polling: which to use

Use a webhook when you run many numbers at once or already have a public server. Use long-poll for tests and short scripts. Our API docs recommend webhooks for production workloads with several activations in flight.

MethodHow it worksGood forWatch out for
WebhookOne signed POST per SMS to your HTTPS URLMany concurrent numbers, servers, queuesNeeds a public URL, signature check and duplicate handling
Long-pollGET /v1/activations/{id}/wait holds the connection for up to 55 s and returns when the code arrivesTest suites, CLI scripts, one number at a timeRepeat the call until your own deadline; the SDK's waitForCode() does this
PollingGET /v1/activations/{id} at your own intervalSimple cron jobs, no inbound traffic allowedAdds delay equal to your interval
Live events (SSE)GET /v1/events streams all account events; reconnect with Last-Event-IDDashboards and workers without a public URLEach connection lasts about 55 s; the last 200 events are kept for 7 days

If you prefer a terminal, the notp command-line tool wraps the same buy-and-wait flow for quick manual checks.

What happens if no SMS arrives

If no SMS reaches the number within the activation window, typically 20 minutes, the activation expires and its cost goes back to your wallet automatically. Your webhook gets nothing for that number, so don't let a test wait forever on a POST that will never come.

  • Give each test its own deadline, shorter than the activation window, and fail with a clear message when it passes.
  • Listen for activation.expired on the live events stream if you want to log the refund.
  • The exact terms, including the card-only rule for refunds of unused balance, are on our refund policy page (last updated 15 November 2026).

Real-SIM numbers usually receive codes, but no number is promised to work with every platform. Use it for your own accounts and follow each platform's terms; some platforms don't allow virtual numbers. Testing your own sign-up flow, as in our post on testing sign-up flows that combine a captcha and an SMS code, is the use this is built for.

Production checklist for an OTP webhook receiver

Before you point real traffic at the endpoint, check these six things:

  1. The route uses a raw body parser and verifies before parsing.
  2. The secret comes from an environment variable or secret store, never from source code or logs.
  3. Invalid, missing and malformed signatures return 401, never 500.
  4. event_id is stored with a unique index, and duplicates return 200.
  5. The handler answers in well under a second and queues slow work.
  6. Logs show the event name and activation id, not the full SMS text or the phone number.

Frequently Asked Questions

How do I verify a webhook signature in Node.js?

Read the request body as raw bytes, compute an HMAC SHA-256 of those bytes with your webhook secret, and compare the result with the signature header in constant time. In Express, use express.raw() on the webhook route so req.body is a Buffer. Reject the request with 401 if the header is missing, malformed or does not match.

Why does my webhook signature verification keep failing?

Usually because the body was parsed before it was hashed. When you hash JSON.stringify of a parsed object, whitespace and escaped characters can differ from the bytes that were signed, so a valid signature looks wrong. Other common causes are using the wrong secret, hashing a string with a different encoding, or a global JSON parser consuming the body first.

Do I need ngrok to test a webhook locally?

Not to test the receiver logic. You can sign a sample body yourself with openssl and the same secret, then POST it to localhost with curl. That checks the signature, tamper and duplicate paths. You only need a tunnel or a deployed server when you want real events from NumberOTP to reach your machine.

How do I stop processing the same webhook twice?

Store the event_id of every event you handle and skip any event whose ID is already stored, while still answering 200. In production, put a unique index on that column so two copies arriving at the same moment can't both be processed. An in-memory set is fine only for a demo on a single process.

Should I use a webhook or long-polling to get an OTP code?

Use a webhook when you handle many numbers at once and already run a public HTTPS server. Use long-polling for test suites and scripts, because one call simply waits until the code arrives with no inbound traffic to secure. Both deliver the same code; the choice is about your infrastructure, not speed.

Get your first OTP pushed to your server

Set a webhook URL under Developer in your dashboard (the developer overview lists every tool), drop in the 16-line receiver, and the next code your app sends arrives as a signed POST. Create a free NumberOTP account and buy your first number with a webhook_url. If no SMS arrives, the activation is refunded automatically.

Frequently Asked Questions

How do I verify a webhook signature in Node.js?+

Read the request body as raw bytes, compute an HMAC SHA-256 of those bytes with your webhook secret, and compare the result with the signature header in constant time. In Express, use express.raw() on the webhook route so req.body is a Buffer. Reject the request with 401 if the header is missing, malformed or does not match.

Why does my webhook signature verification keep failing?+

Usually because the body was parsed before it was hashed. When you hash JSON.stringify of a parsed object, whitespace and escaped characters can differ from the bytes that were signed, so a valid signature looks wrong. Other common causes are using the wrong secret, hashing a string with a different encoding, or a global JSON parser consuming the body first.

Do I need ngrok to test a webhook locally?+

Not to test the receiver logic. You can sign a sample body yourself with openssl and the same secret, then POST it to localhost with curl. That checks the signature, tamper and duplicate paths. You only need a tunnel or a deployed server when you want real events from NumberOTP to reach your machine.

How do I stop processing the same webhook twice?+

Store the event_id of every event you handle and skip any event whose ID is already stored, while still answering 200. In production, put a unique index on that column so two copies arriving at the same moment can't both be processed. An in-memory set is fine only for a demo on a single process.

Should I use a webhook or long-polling to get an OTP code?+

Use a webhook when you handle many numbers at once and already run a public HTTPS server. Use long-polling for test suites and scripts, because one call simply waits until the code arrives with no inbound traffic to secure. Both deliver the same code; the choice is about your infrastructure, not speed.

Need a number right now? Get $0.10 in free credits — no card required.

Sign up free →

Written by

N

Nanami

Nanami is a telecom and digital privacy specialist at NumberOTP with over 8 years of experience in SMS verification systems, virtual phone infrastructure, and online identity protection. He covers OTP security, number masking, developer APIs, and privacy-first verification workflows for businesses and developers worldwide.

Get your first OTP number free

$0.10 in credits on signup. No card required. Works for 800+ platforms.

Get started free →