Skip to content

Test a Streaming TTS Web App on Phones with Localtonet

Stream text-to-speech audio from a Node.js backend, test autoplay and latency on real phones over HTTPS with a Localtonet tunnel, and guard API cost.

Summary in your language
In this article 12 sections
An iPhone and an Android phone showing a text-to-speech play button beside a laptop running a local development environment
Autoplay and streaming behavior should be tested on real iOS and Android browsers, not only in a desktop browser.
Developer Guides · Streaming TTS · Localtonet · 2026

Build a small Node.js text-to-speech backend, stream audio to a plain JavaScript page, and test it on real iPhones and Android phones over a public HTTPS address.

Voice features that work on a laptop often fail on a phone because of autoplay rules, secure-context restrictions, media Range requests, or buffering. A phone on another network also cannot open your localhost server. In this guide we build a vendor-neutral TTS proxy that keeps the provider key on the server, streams MP3 audio progressively, caches clips so they can be seeked with Range requests, and enforces length caps, rate limits and a daily character budget. Then we publish the backend through a Localtonet HTTP tunnel, measure first-byte latency and chunk arrival with curl, a Node script and browser DevTools, and stop the tunnel when testing is done.

🔒 Provider key stays server-side, Basic Auth and rate limits in front 🌐 Public HTTPS address without port forwarding ⚡ Measure latency and buffering instead of assuming it

Why a TTS web app needs real-phone testing over HTTPS

A hosted text-to-speech (TTS) API usually works like this: you send text and a voice identifier over HTTP and receive audio bytes back, commonly MP3, WAV, Opus or raw PCM depending on the provider. Many providers can stream, so the first audio arrives before the whole clip is synthesized. The browser part looks simple: point an <audio> element at a URL and call play(). On a desktop browser opened at http://localhost:3000, it usually just works.

Phones are where the surprises start. Three things differ from desktop testing:

  • Reachability. A phone on mobile data, or on a different Wi-Fi network, cannot reach localhost on your laptop. Even on the same Wi-Fi, a LAN address such as http://192.168.1.20:3000 requires the right firewall rules and still does not reflect how a real user connects.
  • Secure context. Browsers treat http://localhost as potentially trustworthy, so on your laptop features like navigator.mediaDevices.getUserMedia() (microphone capture), AudioWorklet and service workers are available. On a phone loading the same page from a plain http:// LAN address, the page is not a secure context and those APIs are missing or blocked. You can end up with a voice app that "works" in development and fails the moment it runs on a device over plain HTTP.
  • Media behavior. Mobile browsers have strict autoplay policies, they may request audio with HTTP Range headers before playing, and they decide when to start playback based on how much data has arrived. Whether your stream actually plays progressively on Safari for iOS or Chrome for Android is something you have to observe, not assume.

The practical fix is to give your local backend a public HTTPS address for the duration of the test. With Localtonet, our client on your development machine opens an outbound connection to one of our relay servers, and an HTTP tunnel gives the app a public HTTPS URL. There is no router port forwarding, no firewall change and no public IP required, and the URL only works while the client is connected and the tunnel is started. That is a good fit for short, deliberate test sessions on real devices.

How the pieces fit together

Diagram of phone browsers sending a request through a public HTTPS endpoint and Localtonet HTTP tunnel to a Node.js backend on localhost:3000, which calls a TTS API and streams audio back
Requests from the phone reach the local Node.js backend through the tunnel, and audio chunks stream back along the same path.

The app has three parts: a static frontend, a Node.js backend, and a TTS provider. The browser never talks to the provider directly. It calls one route on your backend, /api/speech, which validates the request, checks cost limits, calls the provider with a key stored in an environment variable, and streams the audio back while also writing it to a cache file. When the same text and voice are requested again, the backend serves the cached file, which supports HTTP Range requests and has a known length, so seeking and duration display work.

🔑 Server-side provider key The provider key lives in a .env file read by Node. It is never sent to the browser, so a tester cannot copy it from DevTools and run up your bill elsewhere.
📡 Chunked streaming route The backend pipes provider bytes to the response as they arrive. On HTTP/1.1 without a Content-Length, Node sends the body with chunked transfer encoding, so the browser can start buffering early.
💾 Hash-keyed clip cache Clips are stored under a SHA-256 hash of model tag, voice ID and text. Repeat requests cost nothing at the provider and are served with Range support for seeking.
🧮 Cost guards A per-request character cap, a per-client request limit and a daily character budget bound how much synthesis anyone can trigger through the public URL.
🎛️ Mock provider mode A mock mode streams a local MP3 slowly in small chunks. You can test progressive playback, autoplay and the tunnel without spending a single provider character.
🌐 Localtonet HTTP tunnel A public HTTPS address that points at 127.0.0.1:3000 on your machine, available only while our client is connected and the tunnel is started.

Choosing a playback approach

There is more than one way to play TTS audio in a browser. The right one depends on whether you need a consistent voice, progressive playback, caching or seeking. The table summarizes the trade-offs we rely on in this guide.

Approach Best for Behavior and limits
Web Speech API (speechSynthesis) Throwaway read-aloud buttons No backend or key. Uses voices installed on the device, so output differs between phones and desktops. You cannot obtain the audio bytes, so nothing can be cached or reused.
<audio src="/api/speech?..."> Default path for streamed MP3 Browser handles buffering natively and can start before the response ends. Requires a GET URL, so text goes in the query string. Seeking on a live stream with no length is limited.
MediaSource or ManagedMediaSource with fetch() Fine-grained control, POST bodies, custom buffering You append chunks to a SourceBuffer yourself. Support for audio/mpeg varies by browser and version, so you must feature-detect and keep a fallback.
Fetch full response, then Blob URL Short clips, simplest cross-browser fallback Reliable, but nothing plays until the whole clip has downloaded, so perceived latency equals total synthesis plus transfer time.
Cached file with Range support Replays, seeking, duration display Served with Content-Length and 206 Partial Content responses, which media elements on mobile handle most predictably.

Prerequisites

You need the following before you start. Nothing here is tied to a particular TTS vendor.

  • Node.js 22. The code uses the built-in fetch, the --env-file flag and import.meta.dirname, all available in Node 22, so no extra packages are needed for those.
  • Express 5, installed from npm in the project.
  • A TTS provider account and API key, plus the provider's documentation for its streaming endpoint, authentication header, request body, output formats, per-request character limit, rate limits and data retention. These details differ between providers, and we do not guess them in this guide.
  • A sample MP3 for mock mode. Any MP3 you have the rights to works. If you have ffmpeg installed, you can generate a test tone (shown below).
  • curl for command-line checks.
  • At least one iPhone or iPad and one Android device. For remote debugging, a Mac with Safari for iOS devices, and a desktop with Chrome plus a USB cable for Android.
  • A Localtonet account and the Localtonet client installed on the machine that runs the backend, with that device's AuthToken available in your dashboard.
Why MP3 is the default here

MP3 is the most broadly playable format for an <audio> element on mobile and desktop browsers, and most providers offer it. Some providers recommend raw PCM or WAV for the lowest latency, but those need different handling in the browser (usually Web Audio) and are outside the scope of this walkthrough.

Build the Node.js streaming backend

Create the project

Create one folder for the server and a public folder for the static frontend. The cache folder holds synthesized clips, and samples holds the MP3 used in mock mode.

mkdir -p voice-app/public voice-app/cache voice-app/samples
cd voice-app
npm init -y
npm pkg set type=module
npm install express
printf '.env\nnode_modules\ncache\n' > .gitignore

If you have ffmpeg, generate a 20-second test tone as the mock sample. A tone makes it obvious by ear when playback starts and whether it stutters.

ffmpeg -f lavfi -i "sine=frequency=440:duration=20" -codec:a libmp3lame -b:a 64k samples/sample.mp3

Now create .env. These variable names are defined by our example code, not by any provider. Choose your own long random password for Basic Auth.

PORT=3000
TTS_MODE=mock
TTS_MODEL=default
TTS_API_KEY=replace-with-your-provider-key
BASIC_AUTH_USER=tester
BASIC_AUTH_PASS=replace-with-a-long-random-password
MAX_CHARS=500
DAILY_CHAR_BUDGET=20000
Keep secrets out of the repository and the browser

The .gitignore above excludes .env. Never put the provider key in frontend JavaScript, HTML or query strings. Anyone who loads the page can read client-side code, and a public test URL makes that page reachable from anywhere.

Isolate provider-specific code

All vendor details live in one file, provider.js. It maps friendly voice names to provider voice IDs and returns a Node readable stream of MP3 bytes. In mock mode it streams the sample file in 8 KB chunks with a 50 ms pause between them, which simulates a provider that synthesizes progressively.

// provider.js
import { createReadStream } from 'node:fs';
import { Readable } from 'node:stream';
import { setTimeout as sleep } from 'node:timers/promises';
import path from 'node:path';

// Map friendly names to the voice IDs your provider documents.
const VOICES = {
  narrator: 'replace-with-provider-voice-id-1',
  friendly: 'replace-with-provider-voice-id-2',
};

export function resolveVoice(name) {
  return Object.hasOwn(VOICES, name) ? VOICES[name] : null;
}

// Replace this with the URL, headers and JSON body from your provider's
// streaming TTS documentation. Request MP3 output if the provider offers it.
function buildProviderRequest(text, voiceId) {
  throw new Error('Implement buildProviderRequest() for your TTS provider');
  // Expected return shape: { url: '...', init: { method: 'POST', headers: {...}, body: '...' } }
}

export async function synthesize(text, voiceId) {
  if (process.env.TTS_MODE === 'mock') return mockStream();

  const { url, init } = buildProviderRequest(text, voiceId);
  const res = await fetch(url, init);
  if (!res.ok || !res.body) {
    throw new Error(`Provider responded with HTTP ${res.status}`);
  }
  // Convert the web ReadableStream into a Node stream for piping.
  return Readable.fromWeb(res.body);
}

async function* slowChunks(file) {
  for await (const chunk of createReadStream(file, { highWaterMark: 8192 })) {
    yield chunk;
    await sleep(50);
  }
}

function mockStream() {
  const file = path.join(import.meta.dirname, 'samples', 'sample.mp3');
  return Readable.from(slowChunks(file));
}

We intentionally leave buildProviderRequest() as a function that throws. Authentication schemes, endpoint paths, body fields and streaming parameters differ between providers, and copying a guess from a blog is a common source of silent failures. Fill it in from your provider's API reference once mock mode works end to end.

Write the server

The server does five jobs in order: refuse to start without credentials, require Basic Auth on every request, serve the static frontend, and on /api/speech validate input, then either serve a cached clip or stream a fresh one while caching it.

// server.js
import express from 'express';
import { createHash, timingSafeEqual } from 'node:crypto';
import { createWriteStream, existsSync } from 'node:fs';
import { rename, unlink } from 'node:fs/promises';
import path from 'node:path';
import { pipeline } from 'node:stream/promises';
import { resolveVoice, synthesize } from './provider.js';

const PORT = Number(process.env.PORT ?? 3000);
const MAX_CHARS = Number(process.env.MAX_CHARS ?? 500);
const DAILY_BUDGET = Number(process.env.DAILY_CHAR_BUDGET ?? 20000);
const MODEL_TAG = process.env.TTS_MODE === 'mock' ? 'mock' : (process.env.TTS_MODEL ?? 'default');
const CACHE_DIR = path.join(import.meta.dirname, 'cache');
const AUTH_USER = process.env.BASIC_AUTH_USER ?? '';
const AUTH_PASS = process.env.BASIC_AUTH_PASS ?? '';

if (!AUTH_USER || !AUTH_PASS) {
  console.error('Set BASIC_AUTH_USER and BASIC_AUTH_PASS before starting.');
  process.exit(1);
}

const log = (event, data = {}) =>
  console.log(JSON.stringify({ t: new Date().toISOString(), event, ...data }));

const app = express();

// 1. Basic Auth on everything, including the static page.
function safeEqual(a, b) {
  const x = Buffer.from(a);
  const y = Buffer.from(b);
  return x.length === y.length && timingSafeEqual(x, y);
}

app.use((req, res, next) => {
  const [scheme, encoded] = (req.get('authorization') ?? '').split(' ');
  if (scheme === 'Basic' && encoded) {
    const decoded = Buffer.from(encoded, 'base64').toString();
    const i = decoded.indexOf(':');
    if (i > 0 && safeEqual(decoded.slice(0, i), AUTH_USER) && safeEqual(decoded.slice(i + 1), AUTH_PASS)) {
      return next();
    }
  }
  res.set('WWW-Authenticate', 'Basic realm="tts-test"').status(401).send('Authentication required');
});

// 2. Static frontend.
app.use(express.static(path.join(import.meta.dirname, 'public')));

// 3. Simple fixed-window rate limiter (in memory, fine for testing).
const WINDOW_MS = 60_000;
const MAX_REQUESTS = 10;
const hits = new Map();

function rateLimit(req, res, next) {
  const key = req.ip;
  const now = Date.now();
  const entry = hits.get(key) ?? { count: 0, start: now };
  if (now - entry.start > WINDOW_MS) {
    entry.count = 0;
    entry.start = now;
  }
  entry.count += 1;
  hits.set(key, entry);
  if (entry.count > MAX_REQUESTS) {
    log('rate_limited', { ip: key });
    return res.status(429).set('Retry-After', '60').send('Too many requests');
  }
  next();
}

// 4. Daily character budget for paid synthesis.
let budget = { day: new Date().toISOString().slice(0, 10), used: 0 };

function reserveChars(n) {
  const today = new Date().toISOString().slice(0, 10);
  if (budget.day !== today) budget = { day: today, used: 0 };
  if (budget.used + n > DAILY_BUDGET) return false;
  budget.used += n;
  return true;
}

// 5. The speech route.
app.get('/api/speech', rateLimit, async (req, res) => {
  const text = typeof req.query.text === 'string' ? req.query.text.trim() : '';
  const voiceName = typeof req.query.voice === 'string' ? req.query.voice : 'narrator';
  const voiceId = resolveVoice(voiceName);

  if (!text) return res.status(400).send('text is required');
  if (text.length > MAX_CHARS) return res.status(413).send(`text exceeds ${MAX_CHARS} characters`);
  if (!voiceId) return res.status(400).send('unknown voice');

  const key = createHash('sha256').update(`${MODEL_TAG}\n${voiceId}\n${text}`).digest('hex');
  const cachedFile = path.join(CACHE_DIR, `${key}.mp3`);

  if (existsSync(cachedFile)) {
    log('cache_hit', { chars: text.length, range: req.get('range') ?? null });
    // sendFile sets Content-Length and answers Range requests with 206.
    return res.sendFile(cachedFile, { headers: { 'Cache-Control': 'private, max-age=3600' } });
  }

  if (!reserveChars(text.length)) {
    log('budget_exhausted', { used: budget.used });
    return res.status(429).send('daily character budget reached');
  }

  const started = Date.now();
  let audio;
  try {
    audio = await synthesize(text, voiceId);
  } catch (err) {
    log('provider_error', { message: err.message });
    return res.status(502).send('synthesis failed');
  }

  res.set({ 'Content-Type': 'audio/mpeg', 'Cache-Control': 'no-store' });
  res.flushHeaders();

  const tmpFile = `${cachedFile}.${process.pid}.${started}.tmp`;
  const file = createWriteStream(tmpFile);
  let firstChunk = true;
  let bytes = 0;

  try {
    await pipeline(
      audio,
      async function* (source) {
        for await (const chunk of source) {
          if (firstChunk) {
            firstChunk = false;
            log('first_chunk', { ms: Date.now() - started });
          }
          bytes += chunk.length;
          file.write(chunk);
          yield chunk;
        }
      },
      res,
    );
    await new Promise((resolve, reject) => file.end((err) => (err ? reject(err) : resolve())));
    await rename(tmpFile, cachedFile);
    log('stream_done', { chars: text.length, bytes, ms: Date.now() - started });
  } catch (err) {
    file.destroy();
    await unlink(tmpFile).catch(() => {});
    log('stream_aborted', { chars: text.length, bytes, message: err.message });
  }
});

app.listen(PORT, '127.0.0.1', () => {
  log('listening', { url: `http://127.0.0.1:${PORT}`, mode: process.env.TTS_MODE ?? 'provider' });
});

A few design decisions are worth explaining:

  • The server binds to 127.0.0.1. The only things that can reach it are processes on the same machine, including our Localtonet client. Nobody on your Wi-Fi network can hit it directly, which keeps all outside traffic going through the authenticated public URL.
  • Validation happens before any provider call. Empty text, unknown voices and oversized input are rejected first. The voice whitelist also stops testers from passing arbitrary provider voice IDs.
  • The budget is reserved before synthesis. If a client disconnects halfway, the characters are still counted. That matches the conservative assumption that the provider may bill for a request once it starts. Whether your provider bills for aborted streams is a provider-specific detail you should confirm.
  • The cache only stores complete clips. Audio is written to a temporary file and renamed only after the stream finishes, so an interrupted stream never leaves a truncated MP3 in the cache.
  • The streaming response has no Content-Length. Node uses chunked transfer encoding on HTTP/1.1 in that case. The browser cannot know the duration until the stream ends, which is one reason the cached path exists.

Express 5's res.sendFile() handles Range headers for you and answers with 206 Partial Content plus a Content-Range header. That matters on mobile, where media elements commonly ask for byte ranges before or during playback.

Pronunciation and SSML

Mispronounced names, product terms and abbreviations are the most common quality complaint in TTS apps. How you fix them depends entirely on the provider. Some accept SSML with tags such as phoneme or substitution elements, some offer pronunciation dictionaries, some accept inline phonetic notation, and some steer delivery with natural-language instructions and no SSML at all. Check what your provider supports before designing around it.

If you do pass SSML, two backend concerns follow. First, do not let users submit raw markup: escape user text and wrap it in your own SSML template, otherwise a tester can inject tags that change voice, timing or length. Second, decide whether your character cap counts tags. Some providers bill only spoken characters while others count the markup, and per-request limits may be measured in characters or bytes. Keep the cap on what your backend sends, and update the cache key if the template changes so old clips are not reused.

Build the frontend with gesture-safe playback

The frontend is a single HTML page and one JavaScript module. It offers two ways to play: a plain <audio> element pointed at the streaming URL, and a MediaSource path that fetches the stream and appends chunks itself. It also prints a timestamped event log so you can read results directly on the phone screen.

<!-- public/index.html -->
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>TTS streaming test</title>
</head>
<body>
  <label>Text<br>
    <textarea id="text" maxlength="500" rows="4">Your order has shipped and will arrive on Thursday.</textarea>
  </label>
  <p>
    <label>Voice
      <select id="voice">
        <option value="narrator">Narrator</option>
        <option value="friendly">Friendly</option>
      </select>
    </label>
  </p>
  <button id="speak">Speak (audio element)</button>
  <button id="speak-mse">Speak (MediaSource)</button>
  <p><audio id="player" controls preload="none"></audio></p>
  <pre id="log"></pre>
  <script type="module" src="/app.js"></script>
</body>
</html>
// public/app.js
const player = document.getElementById('player');
const logEl = document.getElementById('log');
const log = (msg) => {
  logEl.textContent += `${(performance.now() / 1000).toFixed(2)}s  ${msg}\n`;
};

log(`isSecureContext=${window.isSecureContext} mediaDevices=${'mediaDevices' in navigator}`);

function speechUrl() {
  const params = new URLSearchParams({
    text: document.getElementById('text').value,
    voice: document.getElementById('voice').value,
  });
  return `/api/speech?${params}`;
}

for (const ev of ['loadstart', 'progress', 'waiting', 'stalled', 'canplay', 'playing', 'ended', 'error']) {
  player.addEventListener(ev, () => log(ev === 'error' ? `error code=${player.error?.code}` : ev));
}

// Path 1: let the browser stream the URL natively.
document.getElementById('speak').addEventListener('click', () => {
  const t0 = performance.now();
  player.src = speechUrl();
  player.addEventListener('playing', () => log(`audible after ${Math.round(performance.now() - t0)} ms`), { once: true });
  // play() is called synchronously inside the click handler.
  player.play().catch((err) => log(`play() rejected: ${err.name}`));
});

// Path 2: fetch and append chunks with MediaSource or ManagedMediaSource.
const MS = window.ManagedMediaSource ?? window.MediaSource;

document.getElementById('speak-mse').addEventListener('click', () => {
  if (!MS || !MS.isTypeSupported('audio/mpeg')) {
    log('MediaSource with audio/mpeg is not available here; use the audio element button');
    return;
  }
  const t0 = performance.now();
  const ms = new MS();
  player.disableRemotePlayback = true; // needed for ManagedMediaSource in Safari
  player.src = URL.createObjectURL(ms);
  player.play().catch((err) => log(`play() rejected: ${err.name}`));

  ms.addEventListener('sourceopen', async () => {
    const sb = ms.addSourceBuffer('audio/mpeg');
    const res = await fetch(speechUrl());
    if (!res.ok) {
      log(`HTTP ${res.status}: ${await res.text()}`);
      return;
    }
    const reader = res.body.getReader();
    let first = true;
    for (;;) {
      const { done, value } = await reader.read();
      if (done) break;
      if (first) {
        first = false;
        log(`first chunk after ${Math.round(performance.now() - t0)} ms`);
      }
      await new Promise((resolve) => {
        sb.addEventListener('updateend', resolve, { once: true });
        sb.appendBuffer(value);
      });
    }
    ms.endOfStream();
    log('stream complete');
  }, { once: true });
});

Why play() lives inside the click handler

Mobile browsers, and Safari in particular, allow audible playback only when it is triggered by a user gesture. If you await a network request and call play() afterwards, the gesture may no longer count and the call rejects with NotAllowedError. Both buttons above assign the source and call play() synchronously in the handler. The browser then waits for data while the promise stays pending, which is allowed. Never try to autoplay synthesized speech on page load: expect it to be blocked on phones, and design for a tap.

Why the main path uses GET

An <audio> element can only load a URL, so the native streaming path needs a GET request with the text in the query string. That is acceptable for a test harness with a 500-character cap, but query strings tend to end up in logs, browser history and intermediary access logs. For production, a common pattern is a POST that validates the text and returns a short-lived clip ID, followed by a GET for that ID. The MediaSource path could also switch to POST because it uses fetch(). We keep both on GET here so the two paths are directly comparable.

MediaSource support is a moving target

Classic MediaSource has historically not been available on iPhone Safari, and recent Safari versions expose ManagedMediaSource instead. Support for audio/mpeg in a SourceBuffer also differs between browsers. Always feature-detect as shown and keep the plain audio element as the fallback. Check current browser compatibility data rather than relying on any fixed list.

Start the app and verify it locally

Start the server with Node's built-in environment file support:

node --env-file=.env server.js

You should see a JSON listening line with http://127.0.0.1:3000 and "mode":"mock". Run the checks below from a second terminal. Replace the password with your own value, and note that passing it on the command line stores it in your shell history, so treat it as a disposable test credential.

Check authentication

curl -i http://127.0.0.1:3000/
curl -i -u tester:YOUR_PASSWORD http://127.0.0.1:3000/

The first call should return 401 with a WWW-Authenticate: Basic header. The second should return 200 and the HTML page.

Check streaming and first-byte time

curl -sS -N -u tester:YOUR_PASSWORD -D - -o /tmp/clip.mp3 \
  -w 'status=%{http_code} ttfb=%{time_starttransfer}s total=%{time_total}s bytes=%{size_download}\n' \
  'http://127.0.0.1:3000/api/speech?text=Hello%20from%20the%20test&voice=narrator'

In mock mode, ttfb should be small and total should be several seconds longer, because the mock pauses 50 ms between 8 KB chunks. The headers should show Content-Type: audio/mpeg and Transfer-Encoding: chunked with no Content-Length. The server log shows first_chunk and stream_done events.

Check the cache and Range support

Repeat the same request. This time the server logs cache_hit, the response includes Content-Length and Accept-Ranges: bytes, and it finishes almost instantly. Then request a byte range explicitly:

curl -sS -u tester:YOUR_PASSWORD -D - -o /dev/null -H 'Range: bytes=0-1' \
  'http://127.0.0.1:3000/api/speech?text=Hello%20from%20the%20test&voice=narrator'

Expect HTTP/1.1 206 Partial Content and a Content-Range: bytes 0-1/... header. That is the behavior media elements depend on for seeking. Note that the streaming route (first request for new text) returns 200 to a Range request, because it has no file yet. That difference is intentional and is one of the things to watch on iOS.

Check the guards

# Unknown voice: expect 400
curl -s -o /dev/null -w '%{http_code}\n' -u tester:YOUR_PASSWORD 'http://127.0.0.1:3000/api/speech?text=hi&voice=nope'

# Over the cap: expect 413
curl -s -o /dev/null -w '%{http_code}\n' -u tester:YOUR_PASSWORD \
  "http://127.0.0.1:3000/api/speech?text=$(printf 'a%.0s' $(seq 1 501))"

# Rate limit: the 11th request within a minute should print 429
for i in $(seq 1 11); do
  curl -s -o /dev/null -w '%{http_code} ' -u tester:YOUR_PASSWORD "http://127.0.0.1:3000/api/speech?text=rate%20test%20$i"
done; echo

Finally, open http://localhost:3000 in a desktop browser, sign in, and press both buttons. The log should show isSecureContext=true, because localhost is treated as trustworthy. Remember that this is exactly the result that does not carry over to a phone loading a plain http:// LAN address.

Publish the backend with a Localtonet HTTP tunnel

Localtonet console showing a connected HTTP/s tunnel from https://example.localto.net to 127.0.0.1 port 3000 with status OK
The HTTP tunnel forwards the public HTTPS URL to the Node.js backend on port 3000.

With the backend verified at 127.0.0.1:3000, the next step is a public HTTPS address that phones on any network can use. With Localtonet, our client runs on the same machine as the backend, connects outbound to the relay server you select, and an HTTP tunnel forwards public HTTPS requests to the local IP and port you specify. HTTP tunnels can use a Random Sub Domain, a Custom Sub Domain, or a Custom Domain as the Process Type; all three serve the same content at a public HTTPS address.

Keep the backend running, then follow the setup sequence below. For the authoritative field-by-field workflow, see the Localtonet HTTP tunnel documentation.

1

Install and connect the Localtonet client

Install the Localtonet app for your operating system on the machine running the backend, and authenticate it with that device's AuthToken from your dashboard. The token identifies this specific device, so keep it private.

2

Open the HTTP tunnel page

In the Localtonet dashboard, go to the HTTP tunnel section to create a new tunnel.

3

Select the Process Type

Choose Random Sub Domain for a quick disposable test address, or Custom Sub Domain or Custom Domain if you want a stable address for repeated sessions. Check our current documentation for custom-domain DNS requirements before using your own domain.

4

Select the AuthToken and server

Pick the AuthToken of the machine running the backend and a relay server from the list available in your dashboard. A server closer to you and your testers generally keeps round trips shorter, which matters when you measure first-byte latency.

5

Enter the local IP and port

Set the local target to 127.0.0.1 and port 3000, matching the address the Node server is bound to.

6

Start the tunnel and copy the public URL

Creating the tunnel does not run it. Press Start, then copy the public HTTPS address shown for the tunnel. Requests to that address reach your backend only while the client is connected and the tunnel is started.

Confirm the public path from your laptop before picking up a phone:

curl -i https://YOUR-TUNNEL-ADDRESS/
curl -sS -N -u tester:YOUR_PASSWORD -D - -o /tmp/public.mp3 \
  -w 'status=%{http_code} ttfb=%{time_starttransfer}s total=%{time_total}s\n' \
  'https://YOUR-TUNNEL-ADDRESS/api/speech?text=Public%20path%20check&voice=narrator'

The first call must return 401. If it returns the page without asking for credentials, stop and fix authentication before sharing the URL. The second call should return audio, and the server log should show the request arriving.

The public URL is reachable by anyone who has it

A tunnel makes your local service reachable from the internet. It does not add authorization to your app. Keep Basic Auth, the character cap, the rate limiter and the daily budget enabled whenever the tunnel is running, share the URL and password only with your testers, and stop the tunnel as soon as the session ends.

Test on real iOS and Android browsers

Open the public HTTPS address on each device, enter the Basic Auth credentials when prompted, and work through the same checklist on every browser you support. Test on mobile data as well as Wi-Fi: cellular latency and variability are what real users experience, and they expose buffering behavior that a fast home network hides.

Secure context

The first line of the on-page log should read isSecureContext=true mediaDevices=true. For comparison, if you also load the app over a plain http:// LAN address (temporarily binding the server to your LAN interface), you will typically see isSecureContext=false, and on many mobile browsers navigator.mediaDevices is undefined. That is the reason microphone capture for a voice assistant, AudioWorklet-based processing and service workers must be tested over HTTPS.

Autoplay and gestures

Tap the audio element button. Playback should start after the tap and the log should show playing and the "audible after" time. To confirm the gesture rule on your own devices, try an experiment in DevTools: wrap the play() call in a setTimeout of a second or two, or move it after an await fetch(). On Safari you will usually see play() rejected: NotAllowedError. Remove the experiment afterwards. If you plan a flow that plays several clips in sequence, test that too: reusing the same element that was started by a gesture tends to behave better than creating new elements later.

Progressive playback

Mock mode is the best tool here, because the 20-second tone takes several seconds to deliver. If "audible after" is short and the tone starts while progress events are still arriving, the browser is playing progressively. If audio starts only after the full transfer (roughly the total time you measured with curl), something is waiting for the complete response. Note which browser does it, then use the measurement section below to find out where.

Repeat with the MediaSource button. Where supported, the log shows "first chunk after" and the point where playback starts. Where it is not supported, the log says so and you know the fallback is required on that browser.

Seeking and replay

After a clip has streamed once, press the audio element button again with the same text. The cached file now has a known length, so the player should show a duration and let you scrub. Compare this with the first, streamed playback, where the duration is often unknown or grows as data arrives. If a browser refuses to play the streamed response but plays the cached one, you have found a Range-related difference, which is covered in troubleshooting.

Remote debugging on devices

The on-page log covers a lot, but sometimes you need the full Network panel. For Android, enable USB debugging on the device, connect it to a desktop, and open chrome://inspect in desktop Chrome to inspect the phone's tab. For iPhone and iPad, enable Web Inspector in the device's Safari advanced settings, connect it to a Mac, and open the device from the Develop menu in desktop Safari. Both give you request timing, headers and console output from the real mobile browser.

Check What to look for Where to see it
Secure context isSecureContext=true and mediaDevices present over the HTTPS address First line of the on-page log
Gesture-driven playback No NotAllowedError when play() runs in the tap handler On-page log, remote console
Progressive start "audible after" well below total transfer time On-page log versus curl total
MediaSource path Feature detection result and first-chunk time On-page log
Range and seeking 206 responses and a scrubbable duration on cached clips Remote Network panel, server cache_hit logs with range

Measure first-byte latency and buffering end to end

Timeline diagram from tapping play to playback start, marking time to first byte, tunnel transit, and buffering before playback
Separate measurements for first byte, tunnel transit, and buffering show where streaming delay comes from.

Every hop between the provider and the speaker can add latency or buffering: the provider's model, your backend, the tunnel path, the mobile network and the browser's own buffering decisions. We recommend measuring each layer instead of assuming how any proxy, including a tunnel, handles chunked responses. The goal is a simple comparison: does a chunk that leaves your backend at time T arrive at the client close to T, or does it arrive in one burst at the end?

A chunk-timing script

This small Node script requests a URL and prints when each chunk arrives and how large it is. Run it against the local address and then against the public address, with the same uncached text.

// measure.mjs  usage: node measure.mjs URL USER PASSWORD
const [url, user, pass] = process.argv.slice(2);
const t0 = performance.now();
const res = await fetch(url, {
  headers: { Authorization: 'Basic ' + Buffer.from(`${user}:${pass}`).toString('base64') },
});
console.log(`status=${res.status} headers after ${Math.round(performance.now() - t0)} ms`);
let total = 0;
for await (const chunk of res.body) {
  total += chunk.length;
  console.log(`${Math.round(performance.now() - t0)} ms  +${chunk.length} bytes  (total ${total})`);
}
console.log(`done after ${Math.round(performance.now() - t0)} ms`);
node measure.mjs 'http://127.0.0.1:3000/api/speech?text=Timing%20run%20one&voice=narrator' tester YOUR_PASSWORD
node measure.mjs 'https://YOUR-TUNNEL-ADDRESS/api/speech?text=Timing%20run%20two&voice=narrator' tester YOUR_PASSWORD

Use different text for each run, otherwise the second run is a cache hit and tells you nothing about streaming. In mock mode, the local run shows chunks spread across several seconds. Compare the public run against it:

  • Chunks spread over time, offset by a roughly constant delay: the path is passing data through progressively, and the offset is your network round trip.
  • One or a few large chunks at the very end: something on the path is buffering the response. Record it, and check where: run the script from a different network, inspect the browser's Network timing, and check your own backend's logs for when first_chunk fired.
  • Chunk sizes differ between local and public runs: that alone is normal. Intermediaries and TCP may regroup bytes; what matters is timing, not chunk boundaries.

Separating provider latency from network latency

Once you switch to a real provider, the server's first_chunk log records the time from calling the provider to receiving its first bytes. The client-side first chunk time minus that value approximates the overhead of your backend plus the network path. Providers often quote model latency figures that exclude your network round trip, so your measured numbers will be higher; measure rather than relying on quoted figures.

Reading browser DevTools correctly

In the Network panel, select the /api/speech request and open its Timing view. The waiting phase (time to first byte) reflects how quickly the backend started responding, and the content download phase shows how long the body took to arrive. A long download phase with early playback is good progressive behavior; a long wait with an instant download suggests buffering. Two cautions: the public side of the connection may use a different HTTP version than your local server, and HTTP/2 and HTTP/3 do not use a Transfer-Encoding: chunked header at all, so do not conclude anything from that header's absence in the browser. Rely on timing instead. Media requests may also appear as several entries if the browser issues Range requests.

Throttling is not a substitute for a phone

Desktop network throttling is useful for quick comparisons, but it does not reproduce mobile browser media pipelines, autoplay rules or cellular variability. Use it to narrow down a problem, then confirm on the actual device over the public HTTPS address.

Protect the endpoint and control API cost

TTS providers bill by usage, commonly per character or per token depending on the model, and a synthesis route is easy to abuse: a script can submit long text in a loop. Once the backend is reachable at a public URL, treat it as an internet-facing service even if it is only meant for a few testers. The backend we built already layers several controls; here is what each one does and what it does not do.

Authentication

Basic Auth over HTTPS keeps casual visitors and crawlers out, and browsers attach the credentials to the page, the <audio> request and same-origin fetch() calls automatically. It is a test-session control, not a user system: there is one shared credential and no logout. Use a long random password, change it between test rounds, and never reuse a real account password. For anything beyond short tests, use proper session authentication.

Input caps and voice whitelist

The MAX_CHARS cap bounds the cost of a single request, and the frontend's maxlength is only a convenience, since anyone can call the API directly. Set the cap below your provider's per-request limit; check whether that limit is defined in characters or bytes, because multi-byte text such as emoji or many non-Latin scripts consumes byte limits faster. If you need long-form text, split it into sentences on the server and synthesize them sequentially rather than raising the cap.

Rate limiting and the shared-IP pitfall

The limiter keys on req.ip. Behind a tunnel or any reverse proxy, the connection your Node process sees may come from the local client rather than from each phone, which would put all testers into one bucket. We do not assume which headers carry the original client address on the path to your backend. Log req.ip and the request headers during a test from two different devices and look at what actually arrives. Only enable Express's trust proxy setting for a forwarding header after you have confirmed it is present and cannot be supplied by the client to spoof another address. With a single shared Basic Auth user, a single shared bucket is an acceptable and conservative default for testing.

Daily budget, caching and logging

The daily character budget is the real cost ceiling: even if the rate limiter is misconfigured, synthesis stops once the budget is used. The cache reduces cost further, because repeated text is served from disk. Every request logs its character count, so you can total usage per test session and compare it against your provider's usage dashboard. The in-memory counters reset when the process restarts, which is fine for a test harness and a reason not to use this code unchanged in production. Also consider privacy: the logs record character counts, not text, but the query string containing the text may appear in access logs along the request path.

Provider-side settings

Where your provider supports it, create a separate API key for testing, set a spending or usage cap on the account, and review its data retention options. These controls belong to the provider, so their availability and names vary.

Stopping the tunnel

The simplest control is not being reachable. When a test session ends, stop the tunnel from the dashboard, or delete it if you will not reuse it, and stop the Node process. A stopped tunnel no longer forwards requests, and the backend bound to 127.0.0.1 is not reachable from your LAN either. If you want visibility into tunnel state, our platform-wide webhooks can POST a notification when a token or tunnel in a selected Token Group changes to Connected or Disconnected, with a JSON body containing Id, ActionDate, Type and Status; see the Localtonet webhook documentation. If you work with an AI coding assistant, our Localtonet MCP Server lets assistants such as Claude Code create, start and stop tunnels from the assistant, which makes "stop the tunnel when done" part of the same workflow.

Before switching from mock mode to a paid provider

Confirm that the public URL returns 401 without credentials, that oversized text returns 413, that the eleventh rapid request returns 429, and that DAILY_CHAR_BUDGET is set to an amount you are comfortable spending. Then change TTS_MODE, implement buildProviderRequest() and restart the server.

Troubleshooting

play() rejected: NotAllowedError

Playback was not tied to a user gesture. Make sure play() is called synchronously in the click or tap handler, not after an await, timer or promise chain. Do not attempt playback on page load.

error code=4 or NotSupportedError

The browser could not use the source. Check that the response really is MP3 with Content-Type: audio/mpeg, that the provider was asked for MP3 output, and that the route did not return a text error (for example 401, 413 or 429) instead of audio. The MediaSource button logs the error text; for the plain element, inspect the request in the Network panel.

Audio starts only after the whole clip downloads

Run measure.mjs locally and through the public URL with new text. If chunks arrive spread out locally but in a burst publicly, something on the path is buffering; if they also burst locally, the provider or your adapter is buffering, for example by awaiting the full body before returning. If both look progressive but one browser still waits, that browser's media pipeline is choosing to buffer more data before starting, which is browser behavior you can only accommodate, for example by trying the MediaSource path or shorter sentences.

The streamed clip fails on iPhone but the cached replay works

Safari's media stack makes byte-range requests and works best with a known length. The streaming route answers Range requests with a full 200 response of unknown length, while the cached route answers 206. If your target browsers reject the live stream, options include using the MediaSource path where available, synthesizing short sentences so the fallback "fetch fully then play" path stays fast, or pre-generating clips for fixed text. Verify any fix on the device itself.

The public URL shows an error instead of the app

Check, in order: the Node process is running and printed listening; it is bound to 127.0.0.1 on port 3000; the tunnel's local target matches that IP and port; the Localtonet client on the machine is connected with the right AuthToken; and the tunnel is started, not only created.

Every tester hits 429 at once

All requests are probably sharing one req.ip. That is expected with a single shared bucket. Raise MAX_REQUESTS for group sessions, or key the limiter on something you have verified, as described in the rate-limiting section.

Repeated Basic Auth prompts on a phone

Confirm the username and password have no trailing spaces and that the password does not contain a colon in the username part. Some mobile browsers keep stale credentials for a site; close the tab or clear site data and sign in again. If a tester uses an in-app browser from a messaging app, ask them to open the link in the system browser, which is also where you should be testing autoplay.

Mock audio keeps playing after switching to the provider

The cache key includes a model tag, which is mock in mock mode, so provider clips use different keys. If you changed voice mappings, SSML templates or provider settings without changing TTS_MODEL, old clips may still match. Delete the contents of the cache folder or bump the tag.

mediaDevices is undefined

The page is not running in a secure context. Load it from the public HTTPS address rather than an http:// LAN address, and check that the log line reports isSecureContext=true.

Frequently asked questions

Why can't I just test on my phone with my laptop's LAN IP?

You can reach the page that way on the same Wi-Fi, but a plain http:// LAN address is not a secure context, so APIs such as microphone capture, AudioWorklet and service workers are unavailable or blocked. It also only works on your local network. A public HTTPS address from a Localtonet HTTP tunnel lets you test the secure-context behavior your users will get, from any network including mobile data.

Does the tunnel buffer my streamed audio?

We recommend not assuming either way for any proxy path. Use the measure.mjs script with uncached text against the local and public addresses and compare chunk arrival times. Spread-out arrival with a constant offset means data is passing through progressively; a single burst at the end means something on the path is buffering, and the comparison tells you which layer to investigate.

Why does my audio play on desktop but not on iPhone?

The most common causes are calling play() outside the tap handler, which triggers NotAllowedError, and media served without Range support or a known length. Keep play() synchronous in the gesture handler, serve cached clips with res.sendFile() so Range requests get 206 responses, and feature-detect ManagedMediaSource instead of assuming classic MediaSource exists.

Which TTS provider should I use?

This guide is intentionally vendor-neutral. Compare providers on per-request text limits, streaming support, output formats, pronunciation controls such as SSML or dictionaries, latency measured from your own location, pricing and data retention. Because all provider code lives in buildProviderRequest() and synthesize(), you can switch providers without touching the server routes or frontend.

How do I keep testers from running up my TTS bill?

Combine authentication, a per-request character cap, a per-client rate limit, a daily character budget enforced on the server, a clip cache, per-request character logging and, where your provider supports it, a separate test key with a spending cap. Then stop the tunnel when the session ends so the endpoint is no longer reachable.

Does the public URL stay online when I close my laptop?

No. A Localtonet tunnel is available only while the selected client device is connected and the tunnel is running. If the machine sleeps, the client disconnects, the Node process stops, or you stop the tunnel, testers can no longer reach the app.

Can I use the Web Speech API instead of a hosted provider?

For a simple read-aloud button, yes. It needs no backend or key. The trade-offs are that it uses whatever voices are installed on each device, so output sounds different across phones and desktops, and it does not give you the audio bytes, so you cannot cache, stream through your own server or store the result.

Test your voice app on real phones with Localtonet

Run the streaming TTS backend in mock mode, publish 127.0.0.1:3000 through a Localtonet HTTP tunnel, and check autoplay, secure-context APIs and progressive playback on iOS and Android over HTTPS. Stop the tunnel when the session ends.

Get Started Free →

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