This tutorial builds an Express.js webhook that detects STOP, UNSTOP, and HELP keyword replies in inbound Twilio SMS messages and responds with carrier-compliant TwiML messages while updating an internal opt-out store. It targets Node.js developers who need to track opt-outs in their own database for compliance with CTIA messaging guidelines. You will handle the three core keyword categories and expose a helper function that other parts of your application can call to check whether a number has opted out before sending.
Prerequisites and Setup
Install the packages with npm install twilio express dotenv and configure your Twilio number's inbound SMS webhook to POST to your Express route. Twilio handles STOP opt-outs automatically at the platform level before your webhook fires, but building your own handler gives you visibility into opt-outs and lets you update your own database in real time for cross-channel suppression. The keyword matching must be case-insensitive and trim whitespace since users type these words with varying capitalization and accidental spaces. Your webhook must return a TwiML response for every inbound message, even opt-out keywords, or Twilio will log a webhook delivery warning.
npm install twilio express dotenv
# Twilio Console: SMS webhook for your number
# https://xxxx.ngrok.io/sms/inbound (POST)
The Complete Code
Normalising the body to uppercase and trimming whitespace before matching against keyword sets catches all common user input variations. A JavaScript Set for each keyword category makes the membership check an O(1) operation regardless of how many synonyms you add. The opt-out store is an in-memory Set in this example and should be replaced with a database write in production so opt-outs survive server restarts. The isOptedOut() function exported at the bottom is what your outbound send functions should call before every client.messages.create() call.
require('dotenv').config();
const express = require('express');
const twilio = require('twilio');
const app = express();
app.use(express.urlencoded({ extended: false }));
const optOutList = new Set();
const STOP_KEYWORDS = new Set(['STOP','STOPALL','UNSUBSCRIBE','CANCEL','END','QUIT']);
const UNSTOP_KEYWORDS = new Set(['START','UNSTOP','YES']);
const HELP_KEYWORDS = new Set(['HELP','INFO']);
app.post('/sms/inbound', (req, res) => {
const from = req.body.From || '';
const body = (req.body.Body || '').trim().toUpperCase();
const twiml = new twilio.twiml.MessagingResponse();
if (STOP_KEYWORDS.has(body)) {
optOutList.add(from);
console.log('Opted out:', from);
twiml.message(
'You have been unsubscribed and will receive no further messages. ' +
'Reply START to resubscribe.'
);
} else if (UNSTOP_KEYWORDS.has(body)) {
optOutList.delete(from);
console.log('Re-subscribed:', from);
twiml.message(
'You are now resubscribed and will receive messages again. ' +
'Reply STOP at any time to unsubscribe.'
);
} else if (HELP_KEYWORDS.has(body)) {
twiml.message(
'For assistance contact support@telphi.com. Reply STOP to unsubscribe.'
);
} else {
twiml.message('Thank you. A team member will follow up shortly.');
}
res.type('text/xml');
res.send(twiml.toString());
});
function isOptedOut(phoneNumber) {
return optOutList.has(phoneNumber);
}
module.exports = { isOptedOut };
app.listen(3000, () => console.log('Opt-out handler on port 3000'));
Testing and Debugging
Send the word STOP from a test phone to your Twilio number and verify the webhook logs the opt-out and returns the unsubscribe confirmation TwiML. Send START immediately after and confirm the number is removed from the opt-out set and the re-subscribe confirmation is returned. Test HELP and an unrecognised keyword to verify each branch of the conditional returns the correct response TwiML. Check the Twilio Console under Messaging Logs to see your TwiML responses alongside the inbound messages for a complete conversation view.
Taking It Further
Replace the in-memory Set with a database table that records the phone number, keyword used, opt-out timestamp, and channel so you have a full compliance audit log. Add a check at the start of every outbound send function that calls isOptedOut() and silently skips or throws an error for opted-out numbers before the Twilio API is ever called. Extend the keyword matching to detect multi-word phrases like "please remove me" using body.includes('REMOVE') substring checks for broader opt-out detection beyond the standard keywords. Synchronise the opt-out list to your CRM, email marketing platform, and any other channels so suppression is consistent across all customer touchpoints.
Contact Telphi Consulting to build a compliant opt-out management system with cross-channel suppression for your Node.js messaging platform.
Ready to Transform Your Business Communications?
Get a free consultation with our VoIP experts and discover how we can help you save costs, improve efficiency, and scale your business.
Comments (0)
Join the discussion and share your thoughts (AI-moderated for quality)
Be the first to comment
No comments yet. Share your thoughts below.