Most local service businesses lose calls every week. The owner is on a roof, the front desk is helping someone in person, or the call comes in after hours. If nobody picks up, a lot of callers simply try the next business in the search results. We wrote about the business side of this in our guide on what a missed call really costs a local business. This post covers the developer side: how to build a small, reliable missed call text back flow with Next.js App Router route handlers and Twilio.
The goal is simple. A customer calls the business number. The call is forwarded to the owner's real phone. If nobody answers, the caller gets a friendly text a few seconds later that says something like "Sorry we missed you, how can we help?" The conversation can then continue by SMS, which many customers prefer anyway.
What you need
- A Next.js project using the App Router (version 13.4 or later)
- A Twilio account with a phone number that supports voice and SMS
- The official
twilioNode helper library - A public HTTPS URL for local testing, such as a tunnel tool, because Twilio has to reach your webhooks
One important note for US numbers: sending business SMS from a standard 10 digit number requires A2P 10DLC registration through Twilio. Do this early, because approval can take time and unregistered traffic may be filtered or blocked by carriers. Toll free numbers have their own verification process.
How the call flow works
Twilio drives everything with webhooks and TwiML, which is a small XML language that tells Twilio what to do with a call.
- A call hits your Twilio number. Twilio sends a POST request to your "incoming call" webhook.
- Your route handler returns TwiML with a
<Dial>verb that forwards the call to the business owner's phone, with a timeout and anactionURL. - When the dial attempt ends, Twilio sends another POST to the
actionURL. That request includes aDialCallStatusparameter. - If the status is
no-answer,busy, orfailed, your code sends an SMS to the caller and returns TwiML that plays a short message or takes a voicemail.
That is the whole idea. The rest is making it safe and pleasant.
Environment variables
Keep secrets out of the code. Add these to .env.local and to your hosting provider:
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token
TWILIO_NUMBER=+15555550100
FORWARD_TO_NUMBER=+15555550199
PUBLIC_BASE_URL=https://example.com
The phone numbers above are placeholders. Use E.164 format for real numbers.
A small TwiML helper
You can build TwiML with the helper library, but plain strings are easy to read for a flow this small. Just make sure you return the right content type.
// lib/twiml.ts
export function twimlResponse(xml: string) {
return new Response(`<?xml version="1.0" encoding="UTF-8"?><Response>${xml}</Response>`, {
headers: { "Content-Type": "text/xml" },
});
}
Validating that requests really come from Twilio
Your webhook URLs are public. Without validation, anyone could POST to them and make your app send texts. Twilio signs every webhook request with the X-Twilio-Signature header, and the helper library can check it.
// lib/verify-twilio.ts
import twilio from "twilio";
export async function readVerifiedTwilioForm(req: Request, path: string) {
const form = await req.formData();
const params: Record<string, string> = {};
form.forEach((value, key) => {
params[key] = String(value);
});
const signature = req.headers.get("x-twilio-signature") ?? "";
const url = `${process.env.PUBLIC_BASE_URL}${path}`;
const valid = twilio.validateRequest(
process.env.TWILIO_AUTH_TOKEN as string,
signature,
url,
params
);
return valid ? params : null;
}
A common gotcha: the URL used for validation must match exactly what Twilio called, including the protocol and any query string. Behind a proxy, req.url may show an internal host, which is why this example builds the URL from a known public base.
Route handler 1: the incoming call
// app/api/voice/incoming/route.ts
import { twimlResponse } from "@/lib/twiml";
import { readVerifiedTwilioForm } from "@/lib/verify-twilio";
export async function POST(req: Request) {
const params = await readVerifiedTwilioForm(req, "/api/voice/incoming");
if (!params) return new Response("Forbidden", { status: 403 });
return twimlResponse(`
<Dial timeout="20" action="/api/voice/after-dial" method="POST" callerId="${process.env.TWILIO_NUMBER}">
<Number>${process.env.FORWARD_TO_NUMBER}</Number>
</Dial>
`);
}
The timeout value is in seconds. Twenty seconds is roughly four or five rings. If the owner's cell phone has voicemail enabled and it picks up before the timeout, Twilio will see the call as answered, so set the Twilio timeout shorter than the carrier voicemail delay, or the text back will never fire.
Route handler 2: after the dial attempt
// app/api/voice/after-dial/route.ts
import twilio from "twilio";
import { twimlResponse } from "@/lib/twiml";
import { readVerifiedTwilioForm } from "@/lib/verify-twilio";
import { shouldTextBack } from "@/lib/text-back-guard";
const client = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
const MISSED = new Set(["no-answer", "busy", "failed"]);
export async function POST(req: Request) {
const params = await readVerifiedTwilioForm(req, "/api/voice/after-dial");
if (!params) return new Response("Forbidden", { status: 403 });
const status = params.DialCallStatus;
const caller = params.From;
if (!MISSED.has(status)) {
return twimlResponse("<Hangup/>");
}
if (caller && (await shouldTextBack(caller))) {
try {
await client.messages.create({
to: caller,
from: process.env.TWILIO_NUMBER,
body: "Hi, sorry we missed your call. How can we help? Reply here and we will get right back to you.",
});
} catch (err) {
console.error("Text back failed", err);
}
}
return twimlResponse(`
<Say>Sorry we missed you. We just sent you a text message, or you can leave a voicemail after the tone.</Say>
<Record maxLength="120" playBeep="true" />
`);
}
Notice that a failed SMS never breaks the call. The caller still hears a message and can leave a voicemail. Webhooks should always return valid TwiML quickly, so log errors and move on.
Avoiding duplicate and unwanted texts
If the same person calls three times in five minutes, they should not get three identical texts. A small guard fixes that. Here is a minimal version using any key value store with expiry, such as Redis or Vercel KV. The interface below is intentionally generic.
// lib/text-back-guard.ts
import { kv } from "@/lib/kv"; // your key value client
const COOLDOWN_SECONDS = 60 * 60 * 6; // six hours
export async function shouldTextBack(phone: string) {
if (!phone.startsWith("+1")) return false; // only US and Canada numbers in this example
const key = `textback:${phone}`;
const seen = await kv.get(key);
if (seen) return false;
await kv.set(key, "1", { ex: COOLDOWN_SECONDS });
return true;
}
A few more things worth handling:
-
Blocked or anonymous callers.
Frommay be missing or a placeholder value. Skip the text when it is not a valid E.164 number. - Landlines. A text to a landline goes nowhere. Twilio's Lookup API can return line type information if you want to filter these, but it is a paid lookup, so decide whether it is worth it for your volume.
- Opt out. Twilio handles standard keywords such as STOP on long code numbers by default. Do not build anything that keeps texting someone who opted out, and check messaging rules that apply to your business before going live.
Handling replies
When the caller texts back, Twilio sends a POST to the messaging webhook configured on the number. The simplest useful version forwards the message to the owner and stores it.
// app/api/sms/incoming/route.ts
import twilio from "twilio";
import { readVerifiedTwilioForm } from "@/lib/verify-twilio";
const client = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
export async function POST(req: Request) {
const params = await readVerifiedTwilioForm(req, "/api/sms/incoming");
if (!params) return new Response("Forbidden", { status: 403 });
await client.messages.create({
to: process.env.FORWARD_TO_NUMBER as string,
from: process.env.TWILIO_NUMBER,
body: `New text from ${params.From}: ${params.Body}`.slice(0, 1500),
});
return new Response("<Response></Response>", { headers: { "Content-Type": "text/xml" } });
}
In production you would usually save the thread to a database and show it in a small inbox, or push it into the CRM the business already uses. That way the owner can answer from a laptop instead of juggling two phone numbers.
Wiring it up in the Twilio console
- Open your phone number's configuration.
- Under voice, set "A call comes in" to Webhook, HTTP POST,
https://your-domain/api/voice/incoming. - Under messaging, set "A message comes in" to
https://your-domain/api/sms/incoming. - Save, then call the number from a phone that is not the forwarding number and let it ring out.
Check the Twilio call logs and your hosting logs if nothing happens. Most problems come from a signature mismatch caused by the wrong base URL, or from the forwarding phone's voicemail answering first.
Deployment notes for Vercel and similar hosts
- Route handlers run as serverless functions, so keep them fast. Twilio expects a webhook response within about 15 seconds.
- Do not export route handlers that depend on the Edge runtime unless you have confirmed the helper library works there. The default Node.js runtime is the safe choice.
- Add basic monitoring. A text back flow that silently breaks is worse than none, because the business thinks it is covered.
Where to go from here
This flow is a solid first step. Once it works, many businesses want more: an AI voice agent that answers the call, books the appointment, and only texts back when it truly cannot help. That is the direction our AI receptionist service takes, and the same webhook patterns shown here sit underneath it. If you are building something similar for a client and want a second pair of hands on the backend, our API and backend engineering team works with exactly this kind of integration.
The code above is intentionally small. You can read it in a few minutes, test it in an afternoon, and it solves a real problem for a real business. That is often the best kind of software to ship.
Thanks for reading.
CodeHunterz Team
Top comments (0)