This tutorial builds an Express.js web application with an HTML form that sends a Twilio SMS when a user submits a phone number and message, covering input validation, credential management, and error feedback to the browser. It targets developers who want to give non-technical team members a browser-based interface for sending messages without exposing the Twilio API directly. You will build a form with server-side E.164 validation, a Twilio send call, and JSON error responses that display clearly to the user.
Prerequisites and Setup
Install the packages with npm install twilio express dotenv and load your Twilio credentials from a .env file so they are never exposed in client-side code or HTML. The Express app needs both express.urlencoded() for form POST bodies and express.json() if you plan to drive it from a JavaScript fetch call instead of a traditional form submit. Validate the submitted phone number on the server with a regex before calling the Twilio API to give users a clear E.164 format error instead of a raw Twilio exception. Never pass credentials through the browser or expose the Twilio Auth Token in any client-rendered JavaScript.
npm install twilio express dotenv
# .env
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token_here
TWILIO_PHONE_NUMBER=+15551234567
The Complete Code
The GET route at / serves an HTML form with a phone number input and a textarea for the message body, keeping all rendering server-side without a front-end build step. The POST handler at /send reads the form fields, validates the phone with a regex, calls client.messages.create(), and returns a JSON response with the message SID on success. On validation failure it returns a 400 JSON response with a descriptive error message so the client can display it without parsing a Twilio exception. Wrapping the Twilio call in try/catch and returning a 500 with err.message ensures the server never crashes on API errors.
require('dotenv').config();
const express = require('express');
const twilio = require('twilio');
const app = express();
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
const client = twilio(
process.env.TWILIO_ACCOUNT_SID,
process.env.TWILIO_AUTH_TOKEN
);
const FROM = process.env.TWILIO_PHONE_NUMBER;
const E164 = /^+[1-9]d{7,14}$/;
app.get('/', (req, res) => {
res.send(
'<!DOCTYPE html><html><body>' +
'<h2>Send an SMS</h2>' +
'<form method="POST" action="/send">' +
'<label>To (E.164)</label><br>' +
'<input name="phone" placeholder="+15551234567" required /><br><br>' +
'<label>Message</label><br>' +
'<textarea name="message" rows="4" cols="40" required></textarea><br><br>' +
'<button type="submit">Send SMS</button>' +
'</form></body></html>'
);
});
app.post('/send', async (req, res) => {
const phone = (req.body.phone || '').trim();
const message = (req.body.message || '').trim();
if (!E164.test(phone)) {
return res.status(400).json({
error: 'Phone must be E.164 format, e.g. +15551234567',
});
}
if (!message) {
return res.status(400).json({ error: 'Message body cannot be empty.' });
}
try {
const msg = await client.messages.create({
body: message,
from: FROM,
to: phone,
});
res.json({ success: true, sid: msg.sid, status: msg.status });
} catch (err) {
res.status(500).json({ error: err.message, code: err.code });
}
});
app.listen(3000, () => console.log('Web app on http://localhost:3000'));
Testing and Debugging
Open a browser at http://localhost:3000, enter a valid E.164 number, type a short message, and click Send SMS. A JSON response with a SID should appear in the browser and the SMS should arrive on the destination phone within seconds. Test validation by submitting without the leading plus sign in the phone number and confirm the 400 JSON error response is returned. On trial accounts, test with a verified number first; submitting an unverified number produces a Twilio 21608 error that is surfaced to the browser as the 500 JSON error response with the error message.
Taking It Further
Add authentication using express-session and a login form so only authorised users can access the send form, preventing unauthorised SMS sends that consume your Twilio budget. Apply a per-IP rate limit using the express-rate-limit package to cap how many messages any single session can send per hour. Log every send attempt to a database with the sender's session ID, destination number, message length, timestamp, and resulting SID for audit and compliance. Replace the plain HTML form with a fetch-based JavaScript front end that shows a success toast or inline error without a full page reload, then redirect the existing POST endpoint to return JSON which the front end can consume.
Contact Telphi Consulting to build a secure internal SMS tool with user management, audit logging, and delivery tracking in Node.js.
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.