Skip to content

Twilio Voice AI Agent on Localhost with Localtonet

Bridge Twilio Media Streams to the OpenAI Realtime API from localhost. One Localtonet HTTPS tunnel carries the webhook and the wss audio stream.

Summary in your language
In this article 12 sections
Tutorials · Twilio Media Streams · Localtonet · 2026

Run the whole phone-call audio path on your laptop: webhook, secure WebSocket and realtime model bridge behind one public HTTPS hostname

A Twilio voice agent needs two endpoints that the internet can reach. The first is an HTTPS webhook that returns TwiML when a call arrives. The second is a secure WebSocket (wss) endpoint that receives the caller's audio for the rest of the call. On a development machine behind NAT, neither is reachable by default. In this guide we build a small Node.js bridge that relays audio between Twilio Media Streams and the OpenAI Realtime API, serve both routes from a single local port, and publish that port through one Localtonet HTTP tunnel. We also cover audio format alignment, request signature validation against the public URL, the tunnel settings and logs that help with debugging, and the failure modes that are specific to long-lived audio WebSockets.

🔒 X-Twilio-Signature validation and server-side API keys 🌐 HTTPS webhook and wss upgrade on one hostname ⚡ No port forwarding, VPN or public IP needed
Smartphone on an active call next to a laptop running a local server terminal and a tunnel console
A phone call answered by a voice agent that runs on a local machine.

How the call path works

Diagram of caller to Twilio, then webhook and WebSocket media stream through one Localtonet tunnel to a localhost bridge connected to the OpenAI Realtime API
One tunnel carries both the HTTP webhook and the WebSocket audio stream to the local bridge.

Most webhook integrations are simple request and response exchanges. A provider sends an HTTP POST, your server answers, and the conversation is over. A phone-based voice agent is different. The first request is an ordinary webhook, but its answer tells Twilio to open a WebSocket that stays connected for the entire call and carries small audio messages in both directions. If that stream stalls, the caller hears silence or choppy speech. There is no retry and no page reload that hides the problem.

The full path for an inbound call looks like this:

Caller --(phone network)--> Twilio
Twilio --HTTPS POST /voice--> public tunnel hostname --> Localtonet client --> 127.0.0.1:5050/voice
       (your server returns TwiML containing <Connect><Stream url="wss://HOST/media">)
Twilio --wss upgrade /media--> public tunnel hostname --> Localtonet client --> 127.0.0.1:5050/media
                                                             |
                                       your bridge opens an outbound wss connection
                                                             v
                                                    OpenAI Realtime API

Three separate network legs are involved, and it helps to keep them distinct when debugging:

  • Twilio to your webhook. A normal HTTPS POST with form-encoded call parameters. Your server must answer quickly with TwiML.
  • Twilio to your media endpoint. A WebSocket handshake that starts as an HTTPS request with an Upgrade header, then becomes a persistent bidirectional connection carrying JSON messages with base64 audio.
  • Your bridge to OpenAI. An outbound WebSocket that your server opens. This leg does not touch the tunnel at all, because outbound connections from your machine already work without any inbound reachability.

Why one hostname is enough

Both inbound legs are HTTPS at the start. The webhook is a POST to /voice, and the media stream begins as an HTTPS request to /media that asks to be upgraded to a WebSocket. Because both arrive on the same scheme and port, a single local HTTP server can handle both routes, and a single public HTTPS hostname can front that server. With Localtonet, that hostname comes from one HTTP tunnel pointed at the local port where your bridge listens. Our HTTP tunnel documentation states that WebSocket connections pass through an HTTP tunnel, so the wss:// upgrade needs no separate tunnel type or extra configuration.

The networking model on our side is straightforward. The Localtonet client on your machine makes an outbound connection to a Localtonet relay server. The relay exposes a public HTTPS address, and traffic arriving there is carried back over that connection to the local IP and port you configured. You do not open router ports, change firewall rules for inbound traffic, or need a public IP address. The public address of an HTTP tunnel has no port number; visitors open it like any other website on the standard HTTPS port, which is what Twilio expects. The tunnel only works while the client is connected and the tunnel is started, which is a useful property for a development workflow: when you stop the tunnel, the public endpoint stops reaching your machine.

📞 Voice webhook Twilio POSTs call details to your HTTPS URL when a call arrives. Your server validates the signature and returns TwiML that starts a bidirectional stream.
🔁 Media Streams WebSocket A persistent wss connection where Twilio sends caller audio and your server sends agent audio back, both as base64 payloads inside JSON messages.
🧠 Realtime model bridge Your server opens an outbound WebSocket to the OpenAI Realtime API, forwards caller audio in, and relays generated audio back to Twilio.
🌐 Localtonet HTTP tunnel One tunnel gives the local port a public HTTPS address with no port number. WebSocket connections pass through it, and the client connects outbound, so no inbound port forwarding or public IP is required.

Prerequisites

You need accounts and tools on three sides: Twilio, OpenAI and Localtonet. Here is the full list for this workflow.

Twilio and OpenAI

  • A Twilio account with a voice-capable phone number. You will configure the number's incoming-call webhook. Trial accounts typically have restrictions on which numbers can call or be called; check your Twilio account status if test calls behave unexpectedly.
  • Your Twilio Auth Token. The signature validation code uses it as the HMAC key. It is shown in the Twilio Console. Treat it as a secret.
  • An OpenAI API key with access to the Realtime API, and the identifier of the realtime model you intend to use. Model names change often, so take the current model ID from OpenAI's documentation rather than from any example, including ours.
  • Node.js and npm. Use a current Long Term Support release. The example uses ES modules and three packages: express, ws and twilio.
  • A phone to place test calls to your Twilio number.

Localtonet

  • A Localtonet account.
  • The Localtonet client installed and connected with an AuthToken on the same machine that runs the bridge, or on a machine that can reach it on the network. When you create the tunnel, you select this device's token in the dashboard.
  • A URL type decision. A Random subdomain needs nothing extra. A Custom subdomain or a Custom domain requires Balance on your Localtonet account. A Custom domain also requires a domain that you have added in DNS Manager.
  • The local port of your bridge. With the example code, that is 5050 on 127.0.0.1.
Check the Free plan warning page before testing with Twilio

Our HTTP tunnel documentation has a section titled "The warning page on the Free plan". Twilio is an automated client: it POSTs to your webhook expecting TwiML and opens the media stream expecting a WebSocket handshake. If it receives an interstitial HTML page instead, the call fails. Read that section of the Localtonet HTTP tunnel documentation for the current conditions under which the page appears and the documented way to avoid it, because we do not restate those details here. Whatever plan you use, confirm with the curl checks in the verification section that a POST to your public /voice URL returns a response from your bridge and not a warning page.

Third-party protocol details

Twilio Media Streams and the OpenAI Realtime API are external services with their own versioning. The message names, field shapes and TwiML rules in this guide reflect their documentation at the time of writing. Before you rely on the code in production, confirm event names, session schema fields and model identifiers against current Twilio and OpenAI documentation. The Localtonet steps are covered separately and follow our own documentation.

Audio format alignment: avoid transcoding

Comparison of a transcoding bridge versus a bridge that passes G.711 μ-law audio straight through to OpenAI Realtime
Matching G.711 μ-law on both sides lets the bridge forward audio without conversion.

The single most effective decision for a responsive voice agent is to make both ends speak the same audio format so that your bridge only moves bytes and never resamples them.

What Twilio sends

According to Twilio's Media Streams documentation, the start message describes the audio as audio/x-mulaw at 8,000 Hz, one channel. Each media message carries a base64-encoded payload of that raw mu-law (G.711 u-law) audio. Mu-law uses one byte per sample, so 8 kHz audio is 8,000 bytes per second, and a 20 millisecond frame is 160 bytes before base64 encoding. Bandwidth is tiny. What matters is how quickly each frame moves through the pipeline.

What the Realtime API can accept

The OpenAI Realtime API supports PCM audio, but its PCM format is documented at a 24 kHz sample rate. Bridging Twilio to PCM would mean decoding 8 kHz mu-law, upsampling to 24 kHz on the way in, and downsampling and re-encoding on the way out, on every frame of every call. That is extra CPU work in the hot path and extra delay per turn.

The Realtime API also accepts G.711 directly. In the current general availability session schema, audio formats are set through nested objects, session.audio.input.format and session.audio.output.format, and the mu-law type is audio/pcmu (A-law is audio/pcma). Older beta-era examples used flat fields such as input_audio_format: "g711_ulaw". If you are adapting an older Twilio sample and the API rejects your session.update, this schema change is the first place to look.

Bridge strategy Work per frame Practical effect
mu-law in, mu-law out (audio/pcmu on both sides) Pass the base64 payload through unchanged Simplest code, no resampler, lowest added processing delay
Twilio mu-law to 24 kHz PCM Decode, upsample, then downsample and re-encode the reply More CPU, more code, more room for quality and timing bugs
Mismatched formats with no conversion None, but the bytes are interpreted incorrectly Static, noise, sped-up or silent audio; a common "connected but broken" symptom

Rules for audio you send back

  • Raw audio only. Twilio expects raw mu-law bytes in the payload. Including file headers, such as a WAV header, corrupts the stream and usually sounds like clicks or static.
  • Any chunk size. Twilio documents that outbound payloads can be any size, so you can forward model output deltas as they arrive.
  • Playback is buffered. Twilio plays outbound media in the order received. Model APIs usually generate audio faster than real time, so audio queues on Twilio's side. That is normal, and it is why interruption handling needs the clear message described below.

Build the local bridge server

The bridge is a single Node.js process that listens on one local port and does four jobs: answer the voice webhook with TwiML, accept and authenticate the Media Streams WebSocket, open a WebSocket to the Realtime API, and relay audio and control messages between the two sockets.

Project setup

mkdir twilio-voice-agent
cd twilio-voice-agent
npm init -y
npm install express ws twilio

Open package.json and add "type": "module" so Node treats the file as an ES module. Then configure the environment variables the example reads. These names are defined by our sample code, not by Twilio or OpenAI, so you can rename them as long as you update the code.

export PORT=5050
export PUBLIC_HOST="your-tunnel-hostname-without-scheme"
export TWILIO_AUTH_TOKEN="paste-your-twilio-auth-token"
export OPENAI_API_KEY="paste-your-openai-api-key"
export REALTIME_MODEL="current-realtime-model-id-from-openai-docs"

PUBLIC_HOST is the hostname of your Localtonet tunnel: the host name shown in the URL column of the dashboard, without https://. You will fill it in after creating the tunnel. Do not include a trailing slash or a path.

The webhook route

The /voice route validates the Twilio signature, generates a one-time nonce for this call, and returns TwiML with a <Connect><Stream> instruction. Two Twilio rules shape this TwiML. First, the stream URL must use wss://; plain ws:// is not supported. Second, the stream URL does not support query string parameters. Per-call data goes in <Parameter> elements, which arrive in the WebSocket start message under customParameters. Twilio documents that each parameter's name plus value must be under 500 characters.

The full example

// server.js
import http from "node:http";
import crypto from "node:crypto";
import express from "express";
import twilio from "twilio";
import { WebSocketServer, WebSocket } from "ws";

const PORT = Number(process.env.PORT || 5050);
const PUBLIC_HOST = process.env.PUBLIC_HOST;           // tunnel hostname, no scheme
const TWILIO_AUTH_TOKEN = process.env.TWILIO_AUTH_TOKEN;
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const REALTIME_MODEL = process.env.REALTIME_MODEL;

// Verify this endpoint against current OpenAI Realtime documentation.
const REALTIME_URL =
  "wss://api.openai.com/v1/realtime?model=" + encodeURIComponent(REALTIME_MODEL);

if (!PUBLIC_HOST || !TWILIO_AUTH_TOKEN || !OPENAI_API_KEY || !REALTIME_MODEL) {
  console.error("Missing required environment variables");
  process.exit(1);
}

// One-time nonces issued by /voice and consumed by the media stream.
const pendingNonces = new Map();

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

app.get("/health", (_req, res) => res.send("ok"));

app.post("/voice", (req, res) => {
  const signature = req.get("X-Twilio-Signature") || "";
  // Validate against the PUBLIC URL Twilio called, not the local one.
  const publicUrl = `https://${PUBLIC_HOST}/voice`;

  if (!twilio.validateRequest(TWILIO_AUTH_TOKEN, signature, publicUrl, req.body)) {
    console.warn("Rejected /voice: invalid X-Twilio-Signature");
    return res.status(403).send("Forbidden");
  }

  const nonce = crypto.randomBytes(16).toString("hex");
  pendingNonces.set(nonce, req.body.CallSid);
  setTimeout(() => pendingNonces.delete(nonce), 60_000);

  const twiml =
    `<?xml version="1.0" encoding="UTF-8"?>` +
    `<Response>` +
      `<Connect>` +
        `<Stream url="wss://${PUBLIC_HOST}/media">` +
          `<Parameter name="nonce" value="${nonce}" />` +
        `</Stream>` +
      `</Connect>` +
    `</Response>`;

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

const server = http.createServer(app);
const wss = new WebSocketServer({ noServer: true });

// Authenticate the WebSocket handshake before accepting it.
server.on("upgrade", (req, socket, head) => {
  const path = (req.url || "").split("?")[0];
  if (path !== "/media") {
    socket.destroy();
    return;
  }

  const signature = req.headers["x-twilio-signature"] || "";
  const publicWsUrl = `wss://${PUBLIC_HOST}/media`;

  if (!twilio.validateRequest(TWILIO_AUTH_TOKEN, signature, publicWsUrl, {})) {
    console.warn("Rejected /media upgrade: invalid X-Twilio-Signature");
    socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
    socket.destroy();
    return;
  }

  wss.handleUpgrade(req, socket, head, (ws) => wss.emit("connection", ws, req));
});

wss.on("connection", (twilioWs) => {
  let streamSid = null;
  let openaiWs = null;

  const closeAll = () => {
    if (openaiWs && openaiWs.readyState === WebSocket.OPEN) openaiWs.close();
    if (twilioWs.readyState === WebSocket.OPEN) twilioWs.close();
  };

  // Close streams that never send a valid start message.
  const startTimer = setTimeout(() => {
    if (!streamSid) closeAll();
  }, 10_000);

  twilioWs.on("message", (raw) => {
    let msg;
    try { msg = JSON.parse(raw); } catch { return; }

    switch (msg.event) {
      case "connected":
        break;

      case "start": {
        const nonce = msg.start?.customParameters?.nonce;
        if (!nonce || !pendingNonces.has(nonce)) {
          console.warn("Rejected stream: unknown or reused nonce");
          closeAll();
          return;
        }
        pendingNonces.delete(nonce);
        clearTimeout(startTimer);
        streamSid = msg.start.streamSid;
        openaiWs = connectRealtime(twilioWs, () => streamSid);
        break;
      }

      case "media":
        if (openaiWs && openaiWs.readyState === WebSocket.OPEN) {
          // Pass mu-law payload through unchanged.
          openaiWs.send(JSON.stringify({
            type: "input_audio_buffer.append",
            audio: msg.media.payload,
          }));
        }
        break;

      case "stop":
        closeAll();
        break;
    }
  });

  twilioWs.on("close", () => {
    clearTimeout(startTimer);
    if (openaiWs && openaiWs.readyState === WebSocket.OPEN) openaiWs.close();
  });
});

function connectRealtime(twilioWs, getStreamSid) {
  const ws = new WebSocket(REALTIME_URL, {
    headers: { Authorization: `Bearer ${OPENAI_API_KEY}` },
  });

  ws.on("open", () => {
    // GA-style session schema. Confirm field names in current OpenAI docs.
    ws.send(JSON.stringify({
      type: "session.update",
      session: {
        type: "realtime",
        model: REALTIME_MODEL,
        output_modalities: ["audio"],
        instructions: "You are a concise, friendly phone assistant.",
        audio: {
          input:  { format: { type: "audio/pcmu" }, turn_detection: { type: "server_vad" } },
          output: { format: { type: "audio/pcmu" } },
        },
      },
    }));
    // Ask the model to greet the caller first.
    ws.send(JSON.stringify({ type: "response.create" }));
  });

  ws.on("message", (raw) => {
    let evt;
    try { evt = JSON.parse(raw); } catch { return; }
    const streamSid = getStreamSid();

    // GA uses response.output_audio.delta; older beta code used response.audio.delta.
    if ((evt.type === "response.output_audio.delta" || evt.type === "response.audio.delta")
        && evt.delta && twilioWs.readyState === WebSocket.OPEN) {
      twilioWs.send(JSON.stringify({
        event: "media",
        streamSid,
        media: { payload: evt.delta },
      }));
    }

    // Caller started talking: drop queued agent audio and stop the current reply.
    if (evt.type === "input_audio_buffer.speech_started") {
      if (twilioWs.readyState === WebSocket.OPEN) {
        twilioWs.send(JSON.stringify({ event: "clear", streamSid }));
      }
      ws.send(JSON.stringify({ type: "response.cancel" }));
    }

    if (evt.type === "error") {
      console.error("Realtime API error:", evt.error);
    }
  });

  ws.on("close", () => {
    if (twilioWs.readyState === WebSocket.OPEN) twilioWs.close();
  });

  ws.on("error", (err) => console.error("Realtime socket error:", err.message));
  return ws;
}

// Bind to loopback: only the local Localtonet client needs to reach it.
server.listen(PORT, "127.0.0.1", () => {
  console.log(`Bridge listening on http://127.0.0.1:${PORT}`);
});

Start it with node server.js. The process prints the local address and waits for traffic.

What each part is doing

Signature validation uses the public URL. Twilio signs the exact URL it called, which starts with https:// and your tunnel hostname. The request that reaches your bridge does not carry that URL intact. Our HTTP tunnel documentation states that your service receives the host name the visitor used, which is the tunnel address, in the Host header. However, TLS ends at the Localtonet server, so the request arrives at your bridge over plain HTTP. If you rebuild the URL from req.protocol and the Host header, you typically get http:// instead of https://, and the signature never matches. If you ever override the Host request header in the tunnel's Headers settings, the host part changes as well. Building the URL from PUBLIC_HOST avoids that entire class of bugs. The twilio.validateRequest helper takes the Auth Token, the header value, the full URL and the POST parameters.

The handshake is checked before the socket is accepted. Twilio's documentation states that the server should validate X-Twilio-Signature on Media Streams connections. The example validates it in the upgrade handler against the wss:// URL with no body parameters. Confirm in current Twilio documentation exactly which URL form is signed for the WebSocket request; if validation fails for genuine Twilio traffic, log the header and the URL you computed and compare them with Twilio's reference.

The nonce is a second, independent check. Only a caller that passed the signed webhook receives a nonce, and the nonce is consumed on first use. A stream whose start message lacks a valid nonce is closed before any OpenAI session is opened, which also prevents strangers from burning your model usage.

The OpenAI connection opens only after authorization. The API key is read from the environment, used in the outbound connection header, and never sent to Twilio, the caller or any browser.

Interruption uses clear. Because Twilio buffers outbound audio, an agent that keeps talking after the caller interrupts sounds rude. When the Realtime API reports that the caller started speaking, the bridge sends clear to empty Twilio's playback buffer and response.cancel to stop the model's current reply. For more precise behavior, you can send mark messages after each audio chunk; Twilio echoes marks back as they finish playing, and after a clear it returns marks for audio that was discarded, so you can tell how much of the reply the caller actually heard.

Twilio Media Streams message reference

Message Direction Purpose in the bridge
connected Twilio to server First message after the socket opens; no action needed
start Twilio to server Carries streamSid, media format and customParameters; authorize the call here
media Both directions Base64 mu-law audio; forward inbound to OpenAI, forward model output to Twilio
dtmf Twilio to server Keypad presses on bidirectional streams; inbound only, you cannot send tones back
mark Both directions Label points in outbound audio; Twilio echoes them when played or cleared
clear Server to Twilio Empties Twilio's outbound audio buffer, used for barge-in
stop Twilio to server Stream ended; close the OpenAI socket and clean up

Bidirectional stream behavior worth knowing

  • A <Connect><Stream> stream is bidirectional, and Twilio does not execute any TwiML after <Connect> until your server closes the WebSocket.
  • A call can have only one bidirectional stream active at a time, and bidirectional streams receive only the inbound track (the caller's audio).
  • The stream ends when the call ends or when your server closes the WebSocket. <Stop> does not stop a bidirectional stream.
  • When your server closes the socket, Twilio requests the action URL on <Connect> if you set one; otherwise it continues with whatever TwiML follows <Connect>. This is a clean way to hand off to a human or play a goodbye message.
  • Bidirectional streams cannot be started through Twilio's Stream REST resource; they come from <Connect><Stream> TwiML.

Create the Localtonet HTTP tunnel

Localtonet console showing a connected HTTP/s tunnel from a public URL to 127.0.0.1
The connected HTTP/s tunnel forwards the public URL to the local bridge server.

Twilio requires the media endpoint to accept secure WebSocket connections from the public internet on TCP port 443. A Localtonet HTTP tunnel gives your local port a public HTTPS address with no port number, served with a certificate that we provide and renew, so your bridge can stay on plain HTTP. WebSocket connections pass through an HTTP tunnel, which means one tunnel covers both the https:// webhook and the wss:// stream on the same hostname.

Before you begin, make sure the Localtonet client is running on the bridge machine and connected with its AuthToken, and that node server.js is listening on port 5050. The steps below follow the sequence in the Localtonet HTTP tunnel documentation.

1

Open the HTTP page

In the dashboard, open My Tunnels › HTTP and select Create HTTP Tunnel to open the form.

2

Choose the URL type

Select Random subdomain, Custom subdomain or Custom domain. A Random subdomain gives you a generated name on the selected domain and needs nothing extra. A Custom subdomain lets you type the name yourself (letters, digits and hyphens) and requires Balance. A Custom domain uses a domain of your own and requires Balance and a domain added in DNS Manager. All three keep their hostname until you delete the tunnel, so any of them works as a fixed Twilio webhook target.

3

Choose the device and the region

In Device token, select the token used by the Localtonet app on the machine running the bridge. In Server region, choose a region close to your device for lower latency. Pick from the options your dashboard lists rather than a value copied from an article.

4

Enter the local address and create the tunnel

Set Domain (for Custom domain the list only contains your own domains), Subdomain if you chose Custom subdomain, Local IP address and Local port. With the example code, use 127.0.0.1 and port 5050. The form also accepts other IPv4 or IPv6 addresses or localhost, and ports from 1 to 65535. Both /voice and /media are served from this single port, so one tunnel is enough. Select Create tunnel; it appears under Your tunnels as Tunnel # followed by its ID.

5

Start the tunnel

Creating a tunnel does not start it. Select the start button in the Actions column. When the tunnel runs, its address in the URL column becomes a link. If the Localtonet app of that token is offline, a dialog tells you so; start the app, or select Start anyway and the tunnel goes live when the app connects. The tunnel keeps this hostname until you delete it, and stopping and starting it does not change the address.

Once the tunnel is running, copy the host name from the URL column, put it into PUBLIC_HOST without https://, and restart the bridge so that signature validation and the TwiML stream URL both use it. Because the hostname survives stop and start, you normally do this once per tunnel, not once per session.

The same hostname, two schemes

If the URL column shows https://myapp.localto.net, your webhook URL is https://myapp.localto.net/voice and your stream URL is wss://myapp.localto.net/media. The hostname is identical; only the scheme changes, and neither URL needs a port number. The bridge itself speaks plain HTTP and WebSocket locally, because TLS ends at the Localtonet server and the request then travels through the tunnel to your device.

If you use the Custom domain URL type, add the domain in DNS Manager and follow the custom domain instructions in our documentation before pointing Twilio at it. We do not reproduce exact DNS records here because they should be taken from the dashboard and documentation for your account.

HTTP tunnel settings that matter for this workflow

Select the settings button in the Actions column to open the Tunnel settings panel. Under Tunnel Details you can rename the tunnel and change the local IP address and port without recreating it, which keeps the hostname Twilio already knows. The following settings are the ones most relevant to a voice agent.

Setting What it does Relevance to Twilio
Is Only Https? Serves the public URL over HTTPS only and redirects http:// requests to https://. While it is off, the address answers on both. Recommended. Twilio signs the https:// URL, so keeping the public address HTTPS-only avoids accidental plain-HTTP configurations. Still configure Twilio with the https:// URL directly.
HTTP Timeout How long the server waits for a response from your local application, from 1 to 600 seconds. Your /voice route should answer well within any timeout. Our documentation describes this setting in terms of responses from your local application and does not specifically address long-lived WebSockets; if streams close at a consistent duration, review this value and the Activity Log.
Request Log, Activity Log, Tunnel Health Inspect requests, review starts, stops and setting changes, and see the health checks. Shows whether Twilio's POST to /voice and its upgrade request to /media reached the tunnel at all, which separates tunnel problems from bridge problems.
Basic Authentication? Asks visitors for a username and password. If enabled, Twilio's webhook and handshake requests must still be able to pass. Confirm in Twilio's documentation whether and how it can send credentials for both legs before turning this on; otherwise rely on signature validation in your code.
IP Restriction Controls which client IP addresses can access the tunnel. Twilio's Media Streams documentation says your server must accept connections from any public IP address, so a restrictive allowlist is likely to block calls. Do not guess Twilio address ranges.
Headers (Host) Manages custom request and response headers. By default your service receives the tunnel hostname in the Host header. Leave the Host header alone for this bridge. It does not change what Twilio signs, but code that reads the host would see a different value.

Note that changing Is SslStream? or Legacy Connect? on a running tunnel restarts it, so the Localtonet app must be connected. Neither is needed here: the bridge listens on plain HTTP, so Is SslStream? stays off.

Point your Twilio number at the tunnel

With the bridge running and the tunnel started, tell Twilio where to send incoming calls.

  1. In the Twilio Console, open your phone number's configuration.
  2. In the voice section, set the handler for incoming calls to a webhook with the URL https://YOUR_PUBLIC_HOST/voice and the method HTTP POST.
  3. Save the configuration.

Twilio's Console layout changes from time to time, so the exact labels may differ from this description. What matters is that the incoming-call webhook is the public tunnel URL with the /voice path and the POST method, because the example's signature check includes the POST body parameters. If you configured GET instead, Twilio would send parameters in the query string and the validation logic would need to change.

You do not configure the wss:// URL in the Console. Twilio learns it from the TwiML your /voice route returns. This is why PUBLIC_HOST must be correct: a hostname from a tunnel you have since deleted produces TwiML pointing at an address that no longer reaches your machine.

Verify end to end

Test each leg separately before placing a call. That way, when a call fails, you already know which layer is healthy.

1. Local server

curl http://127.0.0.1:5050/health

Expected output: ok. If this fails, the bridge is not running or is bound to a different port.

2. Public HTTPS through the tunnel

curl -i https://YOUR_PUBLIC_HOST/health

Expected output: a success status and the body ok, exactly as from the local check. If the local check passes but this one fails, confirm the tunnel is started, the client is connected, and the tunnel targets 127.0.0.1:5050. If the body is an HTML page rather than ok, something in front of your bridge answered instead of it, such as the Free plan warning page; see the prerequisites alert and the troubleshooting section before continuing.

3. Unsigned webhook is rejected by your bridge

curl -i -X POST https://YOUR_PUBLIC_HOST/voice -d "CallSid=CAtest"

Expected: HTTP 403 with the plain-text body Forbidden, and a "Rejected /voice" line in the bridge log. This proves the POST reached your code, that validation is active, and that no interstitial page sits between Twilio and your TwiML. A 200 here means validation is not running, which you must fix before going further. An HTML body with no bridge log line means the request was answered before it reached your server.

4. The WebSocket upgrade reaches the bridge

npx wscat -c wss://YOUR_PUBLIC_HOST/media

Expected: the connection is refused with a 403, and the bridge logs "Rejected /media upgrade". This is the important tunnel check. It confirms that a wss:// handshake on the public hostname is carried through to the local upgrade handler and that unauthenticated sockets are refused. If you see a connection error without any log line on the bridge, the upgrade is not reaching your server; recheck the scheme, hostname and path.

5. Check the tunnel's Request Log

Open the tunnel's Request Log in the Tunnel settings panel. The POST to /voice and the upgrade request to /media from steps 3 and 4 should appear there. Comparing this log with your bridge log tells you which side handled each request. The Activity Log shows when the tunnel was started, stopped or reconfigured, and Tunnel Health shows the health checks.

6. Real call

Call your Twilio number. In a working setup, the Request Log shows Twilio's POST and upgrade, and the bridge log shows the webhook passing validation, the upgrade passing validation, a start message with a valid nonce, and then a continuous flow of media. The model should greet you, and speaking over it should stop its reply within a short moment. Watch the logs for Realtime API error entries; schema mistakes in session.update appear there.

Security checklist

A public URL that triggers paid model usage and reaches a process on your laptop deserves the same care as any internet-facing service. The tunnel makes the service reachable; it does not authorize anyone. Authorization is your code's job.

Never expose the OpenAI API key or Twilio Auth Token

Keep both secrets in server-side environment variables. Do not place them in TwiML, in <Parameter> values, in client-side code, in logs or in screenshots shared with your team. Anyone holding the OpenAI key can spend against your account, and anyone holding the Twilio Auth Token can forge valid webhook signatures.

Validate X-Twilio-Signature against the exact public URL

Twilio computes the signature from the full URL it requested plus the POST parameters, keyed with your Auth Token. Validation fails if any part of the URL differs: scheme, hostname, port, path or a trailing slash. Always build the URL from your configured public hostname. Behind the tunnel your bridge receives the tunnel hostname but over plain HTTP, so request-derived URLs have the wrong scheme. Do not trust forwarded headers to reconstruct it unless you have confirmed exactly what the edge sends, because a header such as X-Forwarded-Host can be spoofed by a client unless the proxy overwrites it.

Reject unauthenticated WebSocket connections

The media endpoint is the expensive one. Check the handshake signature, require a valid one-time parameter in the start message, and close any socket that does not send start within a few seconds. Do not open a model session until the stream is authorized.

Use HTTPS only at the edge

Turn on Is Only Https? in the tunnel settings so the public address never serves plain HTTP. Layered tunnel controls such as Basic Authentication or IP Restriction are useful for other services, but for this workflow they must not block Twilio, so the signature and nonce checks in your code remain the primary defense.

Bind locally and expose only what you need

The example binds to 127.0.0.1, so the bridge is not reachable from other machines on your LAN; only the local Localtonet client forwards traffic to it. Serve only the routes you need. Avoid adding debug endpoints that dump environment variables, session state or call metadata.

Keep logs free of sensitive content

Call parameters include phone numbers, and audio payloads contain the caller's voice. Log event types, stream identifiers and errors, not payloads or full request bodies. If you need transcripts for development, handle them according to your own privacy obligations and the consent rules that apply to recorded calls where you operate.

Stop the tunnel when testing ends

A Localtonet tunnel only reaches your machine while the client is connected and the tunnel is started. When you finish a testing session, stop the tunnel in the dashboard. Stopping keeps the hostname for next time; delete the tunnel only when you no longer need that address. Also consider pointing the Twilio number at a static fallback, so callers do not hit a dead endpoint while your laptop is off.

Control Protects against Where it lives
Webhook signature check Forged call webhooks /voice route
Handshake signature check Random clients opening media sockets HTTP upgrade handler
One-time nonce in customParameters Replayed or unauthorized streams consuming model usage start message handler
Server-side secrets API key and Auth Token leakage Environment variables on the bridge host
Is Only Https? Plain-HTTP access to the public address Tunnel settings panel
Loopback binding LAN access that bypasses the tunnel path server.listen
Stopping the tunnel A forgotten public endpoint reaching your machine Localtonet dashboard

Troubleshooting

Most problems fall into a small set of patterns. Work through them in the order the call path runs: webhook, handshake, stream messages, model session, audio. At each stage, compare the tunnel's Request Log with your bridge log: a request in the Request Log but not in the bridge log points at the path between tunnel and bridge, and a request in neither means Twilio never reached the tunnel.

The call connects, then hangs up or plays an error immediately

This usually means the webhook did not return valid TwiML. Check the bridge log. A "Rejected /voice" line points to signature validation (see below). No log line at all means Twilio did not reach your server: the tunnel may be stopped, the client disconnected, or the Twilio number configured with the hostname of a tunnel you deleted. Check the Request Log to see whether the POST arrived at the tunnel, and check Twilio's call logs and debugger entries for the HTTP status your webhook returned.

Twilio receives HTML instead of TwiML

If Twilio's debugger shows retrieval or document parse errors, for example entries with codes such as 11200 or 12100 (check Twilio's error reference for the exact meaning), and your bridge log has no matching line, something answered Twilio before your bridge did. Run curl -i -X POST https://YOUR_PUBLIC_HOST/voice -d "CallSid=CAtest" and read the body. Your bridge returns a short plain-text Forbidden; an HTML page means an interstitial is in the way. On the Free plan, review the section "The warning page on the Free plan" in our HTTP tunnel documentation for when that page appears and the documented way to avoid it. The same interception would also break the wss:// handshake, because Twilio expects a WebSocket upgrade response, not a web page.

Requests are rejected before they reach the bridge

A 401 or 403 that appears in the Request Log but never produces a bridge log line usually comes from a tunnel-level control. If you enabled Basic Authentication? or IP Restriction on the tunnel, Twilio's requests may be blocked. Turn them off for this tunnel, or confirm that Twilio can satisfy them for both the webhook and the WebSocket handshake.

The stream connects and then immediately closes

Several causes produce this symptom:

  • The handshake was rejected. Look for "Rejected /media upgrade". If genuine Twilio traffic fails here while the webhook passes, compare the computed wss:// URL with what Twilio signs according to its current documentation.
  • The nonce check failed. The nonce expires after 60 seconds and can be used once. If you restarted the bridge between the webhook and the stream, the in-memory map was cleared.
  • The OpenAI socket closed. The example closes the Twilio socket when the Realtime connection ends. An invalid API key, an unknown model ID or a rejected session.update causes this. Log the close code and any error event from OpenAI.
  • An unhandled exception crashed the handler. Wrap parsing in try/catch, as the example does, and watch the process output.

Signature mismatch on every request

  • The URL used for validation is rebuilt from the request. Behind the tunnel, the bridge receives the tunnel hostname over plain HTTP, so req.protocol plus req.get("host") yields an http:// URL. Use https://PUBLIC_HOST/voice.
  • PUBLIC_HOST does not match the tunnel Twilio is calling. Stopping and starting a tunnel keeps its hostname, so this happens when you deleted and recreated the tunnel, switched to a different tunnel, or changed the domain. Update the variable and the Twilio number configuration together.
  • A trailing slash or path difference. /voice and /voice/ are different URLs for signing purposes.
  • The wrong Auth Token. If you use subaccounts or rotated your token, the signing key may differ from the one in your environment.
  • The body was not parsed. The example uses express.urlencoded; without it, req.body is empty and the computed signature cannot match.

The stream never starts: ws versus wss

Twilio supports only wss:// stream URLs. If your TwiML contains ws://, or an http:// or https:// URL, the stream will not connect. Also remember that query strings in the stream URL are not supported; any data you appended as ?key=value belongs in a <Parameter> element instead.

Silence, static or robotic audio

  • Codec mismatch. If the Realtime session is not configured for audio/pcmu on both input and output, the model receives or returns bytes that Twilio interprets as mu-law but are something else. The result is noise or silence. Confirm that your session.update was accepted rather than rejected with a schema error.
  • Old schema fields. Flat beta fields such as input_audio_format are not the GA shape. If the session update is rejected, the session runs with defaults that may not match Twilio's format.
  • Wrong event name. If no audio comes back at all, check which output delta event your API version emits. The example handles both response.output_audio.delta and the older response.audio.delta.
  • Missing streamSid. Outbound media messages must include the stream's streamSid. Sending audio before the start message arrives means there is no valid identifier yet.
  • Headers in the payload. If you generate audio yourself, for example a prerecorded greeting, strip any file header so only raw mu-law bytes are sent.

The agent talks over the caller

Without barge-in handling, Twilio keeps playing every queued chunk the model already produced. Send clear when speech is detected, cancel the model's in-progress response, and use mark messages if you need to know exactly what the caller heard.

Symptom Most likely cause First thing to check
No log line on a call Tunnel stopped or wrong webhook URL curl https://PUBLIC_HOST/health, the Request Log and Twilio number config
Debugger shows retrieval or parse errors, bridge silent An HTML page such as the Free plan warning page returned instead of TwiML Body of curl -i -X POST to /voice
401 or 403 in Request Log, nothing in bridge log Basic Authentication or IP Restriction on the tunnel Tunnel settings panel
403 on genuine webhooks from the bridge Validating against a request-derived URL or a mismatched hostname The URL string passed to validateRequest
Stream opens then closes Handshake, nonce or OpenAI session failure Bridge log lines and OpenAI close code
Stream never opens ws:// or query string in stream URL The TwiML returned by /voice
Static or noise Audio format mismatch session.update accepted with audio/pcmu
Agent ignores interruptions No clear on speech start input_audio_buffer.speech_started handling

Where latency comes from

Round-trip flow showing latency segments from caller through Twilio, the tunnel, the local bridge, and OpenAI Realtime
Each network hop and the model response add to the delay a caller hears.

Callers notice delay as an awkward pause after they stop speaking. It helps to think of the pause as a sum of contributions from each segment of the path, then decide which ones you can influence. We do not publish latency figures for this workflow, because the numbers depend on your location, network, server region, model and settings. Measure your own setup instead.

📱 Caller to Twilio The phone network and Twilio's media handling. Outside your control during development.
🌐 Twilio to the tunnel edge Network distance between Twilio's media infrastructure and the Localtonet server region you selected. Our documentation advises choosing a region close to your device for lower latency; test rather than assume.
💻 Relay to your machine Your local internet connection, Wi-Fi quality and upload bandwidth. A busy home network or a congested hotspot adds jitter in both directions.
⚙️ Bridge processing Usually small if you pass mu-law through untouched. Resampling, heavy logging or synchronous work in the message handler adds delay per frame.
🧠 Your machine to OpenAI Outbound network path plus the model's turn detection and generation time. Turn detection settings strongly affect how long the agent waits before replying.

Practical ways to keep turns short

  • Avoid transcoding. Matching audio/pcmu on both sides removes a whole processing stage.
  • Forward immediately. Send each delta to Twilio as it arrives instead of collecting whole responses.
  • Tune turn detection. The Realtime API offers turn detection options, such as server-side voice activity detection and, in current versions, a semantic mode. Check OpenAI's documentation for available types and parameters, then compare them on real calls.
  • Keep the handler light. Do database writes, analytics and transcript storage asynchronously, off the audio path.
  • Use a wired or stable connection for test calls when you are judging conversational quality, so you are measuring your code rather than your Wi-Fi.
  • Log timestamps, not audio. Recording when the caller's speech ended and when the first outbound audio chunk was sent gives you a per-turn measurement you can compare as you change settings.

Day-to-day operation

Once the path works, a few habits make repeated testing smoother.

Keep the hostname stable

Every hostname change means updating PUBLIC_HOST, restarting the bridge and editing the Twilio number configuration. With Localtonet, an HTTP tunnel keeps its subdomain until you delete the tunnel, and stopping and starting it does not change the address. That holds for a Random subdomain too, so you can configure Twilio once and reuse the same tunnel across sessions. The hostname only changes if you delete and recreate the tunnel, or switch to a different tunnel or domain. If you need to change the local port later, edit it under Tunnel Details instead of creating a new tunnel. A Custom subdomain or Custom domain, both of which require Balance, is a matter of choosing a readable or branded name, not of stability.

Start and stop deliberately

A typical session is: start the bridge, start the tunnel, run your test calls, stop the tunnel. If you start the tunnel before the Localtonet app is connected, the dashboard warns you, and Start anyway makes the tunnel go live as soon as the app connects. Because the tunnel only works while the client is connected and the tunnel is running, closing your laptop also takes the endpoint offline. Twilio will then fail to reach the webhook, so for shared numbers consider a fallback URL or a separate number dedicated to development.

Get notified when the tunnel drops

Our platform-wide webhooks call a URL of yours when a device (AuthToken) or a tunnel connects or disconnects. This is useful if teammates call your development number and need to know when the agent is offline. A webhook belongs to a token group, which you create under My Tokens, and you configure it under Webhooks in the dashboard menu with these switches:

  • Token Webhook Enable sends a request when an AuthToken in the group connects or disconnects, meaning the Localtonet client of that device comes online or goes offline.
  • Tunnel Webhook Enable sends a request when a tunnel belonging to an AuthToken in the group connects or disconnects.
  • Send When Connected and Send When Disconnected choose which state changes are reported. Turn on at least one webhook type and at least one notification type.

Each event is an HTTP POST with a JSON body containing Id (the AuthToken, or the tunnel's numeric ID sent as a string), ActionDate in ISO 8601 format, Type of Token or Tunnel, and Status of Connected or Disconnected. Keep these delivery properties in mind:

  • Requests carry no signature or secret header. Put a long random secret into the URL, for example as a path segment such as /localtonet/<YOUR_SECRET>, and check it in your receiver.
  • A failed call is not retried, so the receiver should be available and answer quickly.
  • A disconnect is reported when Localtonet registers that the client is gone, which can be slightly later than the moment the device lost its connection.
  • The Webhooks menu item is not shown while you work in a team dashboard; use your own account dashboard.
  • A webhook cannot be edited. To change its URL, group or switches, delete it and create a new one.
  • The receiver URL must be reachable from the internet, not localhost or a private address. It can itself be a Localtonet HTTP tunnel, but run it on a different AuthToken than the one you are watching, so the receiver does not go offline together with the device it reports on.

Full details, including an example receiver and a test procedure, are in the Localtonet webhook documentation.

Handle concurrent test calls

The example creates one OpenAI session per Twilio stream, so several simultaneous test calls each get their own pair of sockets. Each call also consumes its own model usage. Keep that in mind before inviting a group to call your development number at the same time.

Extend the agent

Natural next steps include reading dtmf events for keypad menus, closing the stream and using the <Connect> action URL to transfer to a human, and adding function calling in the Realtime session to look up data. Each of these stays inside the same two routes, so the tunnel configuration does not change.

Frequently asked questions

Do I need two tunnels, one for the webhook and one for the WebSocket?

No. WebSocket connections pass through a Localtonet HTTP tunnel, and both the webhook and the WebSocket handshake are HTTPS requests to the same host on different paths. If one local server handles /voice and /media on the same port, a single HTTP tunnel pointed at that port serves both. Use the https:// scheme for the webhook and wss:// for the stream URL.

Will my tunnel URL change when I stop and start the tunnel?

No. An HTTP tunnel keeps its subdomain until you delete the tunnel, including a Random subdomain. Stopping and starting does not change it. The address only changes if you delete and recreate the tunnel or switch to a different tunnel or domain, which is when you would update PUBLIC_HOST and the Twilio number configuration.

Why does Twilio reject my stream URL?

Twilio only supports wss:// stream URLs, and it does not support query string parameters on them. Use the secure scheme, remove any query string, and pass per-call values with <Parameter> elements, which arrive in the start message under customParameters.

Why does X-Twilio-Signature validation fail behind a tunnel?

Twilio signs the public https:// URL it called. Your bridge receives the tunnel hostname in the Host header, but over plain HTTP because TLS ends at the Localtonet server. If you rebuild the URL from the incoming request, the scheme will not match. Validate against the exact public URL, including scheme, hostname and path, built from a configured value rather than from request headers.

Which audio format should I use with the OpenAI Realtime API?

Twilio Media Streams uses 8 kHz mono mu-law. Configuring the Realtime session for G.711 mu-law, audio/pcmu in the current GA schema, on both input and output lets you pass payloads through without resampling. Confirm the field names against current OpenAI documentation, since earlier beta examples used different flat fields.

Is my OpenAI API key exposed through the tunnel?

Not if you follow the pattern in this guide. The key is read from an environment variable and only used on the outbound connection from your bridge to OpenAI. That connection does not go through the tunnel. Never place the key in TwiML, stream parameters, logs or any client-side code.

Is a Localtonet HTTP tunnel a VPN?

No. An HTTP tunnel publishes one local service at a public HTTPS address. Our VPN feature is VPN Manager, a separate private mesh network. For a Twilio voice agent, the HTTP tunnel is the right tool because Twilio must reach your endpoint from the public internet.

Can I use this setup in production?

This guide targets local development. A tunnel works only while the client is connected and the tunnel is running, so a laptop that sleeps takes your agent offline. For anything callers depend on, run the bridge on an always-on host, review error handling and logging, and evaluate availability and latency on your own infrastructure. We make no latency or uptime claims for this workflow.

How do I end the AI conversation and transfer to a person?

Close the Media Streams WebSocket from your server. Twilio then requests the action URL on <Connect> if you set one, or continues with the TwiML that follows <Connect>. Either can return a <Dial> or a closing message. A <Stop> verb does not end a bidirectional stream.

Put your local voice agent on the phone network

Create an HTTP tunnel with Localtonet, point it at your bridge port, and let Twilio reach both your webhook and your secure audio WebSocket through one public HTTPS hostname that stays the same across sessions, without port forwarding or a public IP.

Get Started Free →

Corrections & updates

Substantive changes approved by the Localtonet editorial team are listed transparently below.

Updated the Localtonet tunnel steps to current docs, corrected hostname persistence, and added notes on the Free plan warning page, tunnel settings, and request logs.

Localtonet is a secure multi-protocol tunneling and proxy platform designed to expose localhost, devices, private services, and AI agents to the public internet supporting HTTP/HTTPS tunnels, TCP/UDP forwarding, mobile proxy infrastructure, file server publishing, latency-optimized game connectivity, and developer-ready AI agent endpoint exposure from a single unified control plane.

Support