Real-world examples of Twilio webhooks for SMS you can copy today

If you’re building anything serious with Twilio SMS, you’ll hit webhooks almost immediately. The fastest way to understand them is to look at real, working examples of Twilio webhooks for SMS and see how the request and response actually behave. In this guide, we’ll walk through practical, production-style examples of Twilio webhooks for SMS that you can adapt to your own stack, whether you’re using Node.js, Python, PHP, or something else entirely. Instead of vague theory, we’ll use concrete use cases: auto-replies, 2FA, support queues, opt-in flows, delivery tracking, and more. Along the way, you’ll see how Twilio signs webhook requests, how to validate them, and how to respond with TwiML so your messages behave exactly the way you expect. If you’ve been looking for clear, opinionated examples of examples of Twilio webhooks for SMS that go beyond “Hello World,” you’re in the right place.
Written by
Jamie
Published

Fast examples of Twilio webhooks for SMS in real apps

Let’s start where most developers actually start: with a simple incoming SMS hitting your webhook URL and your code deciding what to do.

Here’s a minimal Node.js example of a Twilio SMS webhook that sends a basic auto-reply:

// server.js
import express from 'express';
import twilio from 'twilio';

const app = express();
app.use(express.urlencoded({ extended: false }));

app.post('/sms/incoming', (req, res) => {
  const MessagingResponse = twilio.twiml.MessagingResponse;
  const twiml = new MessagingResponse();

  const incomingBody = (req.body.Body || '').trim().toLowerCase();

  if (incomingBody === 'help') {
    twiml.message('Reply STOP to unsubscribe. Reply INFO for account details.');
  } else {
    twiml.message('Thanks for your message! Our team will reply shortly.');
  }

  res.type('text/xml');
  res.send(twiml.toString());
});

app.listen(3000, () => console.log('Listening on port 3000')); 

This is one of the best examples for understanding the flow:

  • Twilio sends an HTTP POST to /sms/incoming when someone texts your Twilio number.
  • Your app reads Body, branches on the text, and returns TwiML.
  • Twilio parses the TwiML and sends the final SMS to the user.

You can see more about Twilio’s request parameters in their official docs: https://www.twilio.com/docs/messaging/guides/webhook-request

From here, let’s walk through several real examples of Twilio webhooks for SMS that mirror what teams are actually shipping in 2024–2025.


Auto-reply and keyword routing: the most common examples of Twilio webhooks for SMS

If you look at production systems, some of the most common examples of Twilio webhooks for SMS are keyword-based auto-responders. Think:

  • “Text JOIN to subscribe”
  • “Reply YES to confirm your appointment”
  • “Reply STOP to opt out”

Here’s a Python Flask example of a webhook that handles common keywords and logs them to a database:

from flask import Flask, request, Response
from twilio.twiml.messaging_response import MessagingResponse
import sqlite3

app = Flask(__name__)

def log_keyword(from_number, keyword):
    conn = sqlite3.connect('sms.db')
    c = conn.cursor()
    c.execute('CREATE TABLE IF NOT EXISTS keywords (phone TEXT, keyword TEXT)')
    c.execute('INSERT INTO keywords (phone, keyword) VALUES (?, ?)', (from_number, keyword))
    conn.commit()
    conn.close()

@app.route('/sms/keywords', methods=['POST'])
def sms_keywords():
    incoming = (request.form.get('Body') or '').strip().upper()
    from_number = request.form.get('From')

    log_keyword(from_number, incoming)

    resp = MessagingResponse()

    if incoming == 'JOIN':
        resp.message('You are subscribed. Reply STOP to opt out.')
    elif incoming == 'INFO':
        resp.message('Your profile is up to date. Visit our portal for details.')
    elif incoming == 'STOP':
        resp.message('You have been unsubscribed. No more messages will be sent.')
    else:
        resp.message('Unrecognized keyword. Reply HELP for options.')

    return Response(str(resp), mimetype='text/xml')

if __name__ == '__main__':
    app.run(port=5000)

This pattern shows up everywhere in 2024–2025: marketing campaigns, appointment reminders, and account alerts. These are the best examples to start with if you want something that’s both simple and production-relevant.


Secure examples of Twilio webhooks for SMS: validating requests

By 2025, you really shouldn’t accept webhook traffic without validation. Twilio signs each webhook request using an X-Twilio-Signature header. If you’re exposing anything sensitive—like account actions or internal tools—you want to verify that header.

Here’s a Node.js Express example of validating Twilio’s signature before you touch the payload:

import express from 'express';
import twilio from 'twilio';

const app = express();
app.use(express.urlencoded({ extended: false }));

const twilioAuthToken = process.env.TWILIO_AUTH_TOKEN;

function validateTwilioRequest(req, res, next) {
  const signature = req.headers['x-twilio-signature'];
  const url = 'https://yourdomain.com' + req.originalUrl;

  const isValid = twilio.validateRequest(
    twilioAuthToken,
    signature,
    url,
    req.body
  );

  if (!isValid) {
    return res.status(403).send('Invalid Twilio signature');
  }

  next();
}

app.post('/sms/secure', validateTwilioRequest, (req, res) => {
  const twiml = new twilio.twiml.MessagingResponse();
  twiml.message('Secure endpoint reached.');
  res.type('text/xml').send(twiml.toString());
});

app.listen(3000);

Twilio’s official security guidance is worth reading end-to-end: https://www.twilio.com/docs/usage/security

When people ask for examples of Twilio webhooks for SMS that are ready for production, this validation step is usually the missing piece.


Two-factor authentication (2FA) and one-time codes: real examples from 2024–2025

2FA via SMS has come under scrutiny for SIM-swapping risk, but it’s still heavily used, especially as a backup factor. Many authentication flows use Twilio webhooks to:

  • Accept an incoming SMS containing a code
  • Match that code against a pending login
  • Mark the session as verified

Here’s a stripped-down example of a 2FA verification webhook in Python using Flask:

from flask import Flask, request, Response
from twilio.twiml.messaging_response import MessagingResponse

app = Flask(__name__)

pending_codes = {  # in reality, use a database with TTL
    '+15551234567': '839201'
}

@app.route('/sms/verify', methods=['POST'])
def verify_code():
    from_number = request.form.get('From')
    body = (request.form.get('Body') or '').strip()

    expected = pending_codes.get(from_number)

    resp = MessagingResponse()

    if expected and body == expected:
        resp.message('Your login is verified. You may close this window.')
        pending_codes.pop(from_number, None)
#        # update user session or auth state in your app here
    else:
        resp.message('Invalid code. Please request a new one from the login page.')

    return Response(str(resp), mimetype='text/xml')

if __name__ == '__main__':
    app.run(port=5001)

If you’re handling anything related to health accounts or HIPAA-covered data, combine this with strong security practices and regulatory guidance. For general security patterns, NIST’s digital identity guidelines are a good reference: https://pages.nist.gov/800-63-3/

These 2FA flows are some of the most widely deployed real examples of Twilio webhooks for SMS, especially in fintech, health portals, and internal enterprise tools.


Support queues and ticketing: best examples for conversational SMS

Another category where you see powerful examples of Twilio webhooks for SMS is customer support. Think of a small support team that wants:

  • A shared Twilio number
  • Incoming messages to create tickets
  • Agents to reply from their browser while customers see only the SMS thread

Here’s a conceptual Node.js example of how a webhook might bridge SMS into a support system:

import express from 'express';
import twilio from 'twilio';
import { createTicket, appendToTicket } from './helpdesk.js';

const app = express();
app.use(express.urlencoded({ extended: false }));

app.post('/sms/support', async (req, res) => {
  const from = req.body.From;
  const body = req.body.Body;

  // Lookup existing open ticket by phone number
  let ticket = await findOpenTicketByPhone(from);

  if (!ticket) {
    ticket = await createTicket({
      customerPhone: from,
      initialMessage: body
    });
  } else {
    await appendToTicket(ticket.id, body);
  }

  const twiml = new twilio.twiml.MessagingResponse();
  twiml.message('Thanks for your message. Our support team will reply here.');

  res.type('text/xml').send(twiml.toString());
});

app.listen(3000);

On the outbound side, your support UI can call Twilio’s REST API to send SMS replies, while this webhook keeps the conversation tied to a single ticket. For companies that don’t want to buy a full contact center product, this is one of the best examples of Twilio webhooks for SMS enabling a lightweight but real support workflow.


Opt-in, opt-out, and compliance: examples include health and research messaging

Regulators and carriers care a lot about consent, especially in health, research, and emergency alerts. Some of the most important examples of Twilio webhooks for SMS are opt-in and opt-out flows that:

  • Confirm subscription with a clear message
  • Respect STOP, STOPALL, UNSUBSCRIBE, CANCEL, END, and QUIT
  • Log consent with timestamps

Here’s a simple Flask example of an opt-in flow that could be used for a health information service (not medical advice, just reminders or educational content):

from flask import Flask, request, Response
from twilio.twiml.messaging_response import MessagingResponse

app = Flask(__name__)

subscribers = set()

@app.route('/sms/health', methods=['POST'])
def health_opt_in():
    from_number = request.form.get('From')
    body = (request.form.get('Body') or '').strip().upper()

    resp = MessagingResponse()

    if body == 'JOIN':
        subscribers.add(from_number)
        resp.message('You are subscribed to health tips. Reply STOP to unsubscribe.')
    elif body in ['STOP', 'STOPALL', 'UNSUBSCRIBE', 'CANCEL', 'END', 'QUIT']:
        subscribers.discard(from_number)
        resp.message('You are unsubscribed and will receive no further messages.')
    else:
        resp.message('Reply JOIN to receive health tips, or STOP to opt out.')

    return Response(str(resp), mimetype='text/xml')

if __name__ == '__main__':
    app.run(port=5002)

If you’re sending anything related to health information, it’s worth reading general consumer guidance from reputable sources like Mayo Clinic (https://www.mayoclinic.org) or MedlinePlus from the U.S. National Library of Medicine (https://medlineplus.gov/), and then layering on your legal and compliance review. While those sites don’t talk about Twilio specifically, they shape user expectations around privacy and consent, which your SMS flows should respect.


Delivery tracking and status updates: real examples for logistics and retail

E-commerce, food delivery, and logistics companies lean heavily on Twilio SMS for status updates. Some of the best examples of Twilio webhooks for SMS in this space look like this:

  • Customer gets a text: “Your order is out for delivery. Reply 1 to confirm address, 2 to reschedule.”
  • Customer replies with 2.
  • Your webhook updates the delivery record and triggers a reschedule workflow.

Here’s a Node.js Express example of that pattern:

import express from 'express';
import twilio from 'twilio';

const app = express();
app.use(express.urlencoded({ extended: false }));

app.post('/sms/delivery', async (req, res) => {
  const from = req.body.From;
  const body = (req.body.Body || '').trim();

  const twiml = new twilio.twiml.MessagingResponse();

  if (body === '1') {
    await confirmDeliveryAddress(from);
    twiml.message('Thanks! Your delivery is confirmed for today.');
  } else if (body === '2') {
    await startRescheduleFlow(from);
    twiml.message('We will text you a link to reschedule your delivery.');
  } else {
    twiml.message('Reply 1 to confirm today, or 2 to reschedule.');
  }

  res.type('text/xml').send(twiml.toString());
});

app.listen(3000);

These are practical, high-value examples of Twilio webhooks for SMS: they directly reduce failed deliveries, which saves real money.


Analytics, logging, and error handling: examples include message status callbacks

So far, every example has focused on incoming SMS. But Twilio also uses webhooks for status callbacks on outbound messages. You send an SMS via the API, and Twilio later posts delivery status to your callback URL.

Here’s a simple Flask example of a status callback webhook:

from flask import Flask, request

app = Flask(__name__)

@app.route('/sms/status', methods=['POST'])
def sms_status():
    message_sid = request.form.get('MessageSid')
    message_status = request.form.get('MessageStatus')
    error_code = request.form.get('ErrorCode')

#    # Store or log this in your analytics system
    print(f"Message {message_sid} is now {message_status}, error: {error_code}")

    return ('', 204)  # Twilio doesn't require a body

if __name__ == '__main__':
    app.run(port=5003)

In 2024–2025, teams increasingly pipe these status callbacks into their data stack (Snowflake, BigQuery, etc.) to analyze:

  • Delivery rates by carrier and region
  • Failure reasons (invalid numbers, carrier blocks, etc.)
  • Latency between send and delivered statuses

These aren’t user-facing examples of Twilio webhooks for SMS, but they’re critical for operating at scale and staying on good terms with carriers.


Putting it together: patterns you’ll reuse across all examples

If you scan all the examples of examples of Twilio webhooks for SMS above, a few patterns repeat:

  • Parse the payload consistently. Use Body, From, To, and MessageSid as your primary fields. Treat input as untrusted and normalize it (trim, uppercase, etc.).
  • Respond with TwiML when you want Twilio to send a reply. Your webhook doesn’t send SMS directly; it returns XML and Twilio does the sending.
  • Validate signatures on sensitive endpoints. Any webhook that can change account state or expose data should verify X-Twilio-Signature.
  • Log everything. Every one of the best examples of Twilio webhooks for SMS includes some form of logging or persistence, even if it’s just for debugging.
  • Handle STOP and compliance gracefully. Don’t fight carrier expectations; support standard opt-out keywords.

Once you understand these patterns, you can design your own real examples of Twilio webhooks for SMS for whatever your business needs: education, health reminders, banking alerts, or internal IT notifications.

For general guidance on texting users about health, behavior change, or research, resources like the U.S. Centers for Disease Control and Prevention (https://www.cdc.gov) and Harvard’s public health materials (https://www.hsph.harvard.edu) can help you think about tone, clarity, and frequency—even though they don’t talk about Twilio specifically.


FAQ: common questions about examples of Twilio webhooks for SMS

Q: Can you show a simple example of a Twilio SMS webhook that just echoes the message?
Yes. Here’s a minimal echo example of a Twilio webhook in Node.js:

app.post('/sms/echo', (req, res) => {
  const twiml = new twilio.twiml.MessagingResponse();
  twiml.message(`You said: ${req.body.Body || ''}`);
  res.type('text/xml').send(twiml.toString());
});

This is one of the best examples for testing that your Twilio number, webhook URL, and server are wired up correctly.

Q: Do all examples of Twilio webhooks for SMS need to return TwiML?
No. If you don’t want to send an automatic reply, you can return a 200 or 204 with no body, and Twilio will not send an SMS back. Status callback webhooks for outbound messages often behave this way.

Q: What are some production-ready examples include for SMS error handling?
Production systems often combine inbound webhooks with outbound status callbacks. For example, if a message fails with a carrier error code, your status callback webhook logs it and may trigger a fallback channel (email or push notification) instead of SMS.

Q: Is there a best examples pattern for handling different countries or languages?
A common pattern is to use the From or user profile data to look up locale, then branch inside your Twilio webhook to send language-specific templates. Many global apps maintain translation files and let the webhook select the right one.

Q: Where can I find more examples of Twilio webhooks for SMS?
Twilio’s official docs and GitHub repos include additional code samples and starter apps. But the strongest learning usually comes from adapting real examples—like the ones above—to your own business logic, database, and security requirements.

Explore More Webhooks Usage Examples

Discover more examples and insights in this category.

View All Webhooks Usage Examples