惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Fortinet All Blogs
C
Check Point Blog
GbyAI
GbyAI
博客园 - 司徒正美
爱范儿
爱范儿
N
Netflix TechBlog - Medium
H
Hacker News: Front Page
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Security Latest
Security Latest
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园 - Franky
Recent Announcements
Recent Announcements
P
Privacy International News Feed
T
Tor Project blog
Y
Y Combinator Blog
有赞技术团队
有赞技术团队
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
G
GRAHAM CLULEY
The Hacker News
The Hacker News
N
News and Events Feed by Topic
I
Intezer
The GitHub Blog
The GitHub Blog
S
SegmentFault 最新的问题
T
The Blog of Author Tim Ferriss
PCI Perspectives
PCI Perspectives
S
Secure Thoughts
P
Proofpoint News Feed
Microsoft Security Blog
Microsoft Security Blog
IT之家
IT之家
T
Threat Research - Cisco Blogs
J
Java Code Geeks
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
D
DataBreaches.Net
Hacker News - Newest:
Hacker News - Newest: "LLM"
Last Week in AI
Last Week in AI
H
Help Net Security
L
LangChain Blog
大猫的无限游戏
大猫的无限游戏
Help Net Security
Help Net Security
S
Schneier on Security
T
The Exploit Database - CXSecurity.com
Google Online Security Blog
Google Online Security Blog
Cyberwarzone
Cyberwarzone
T
Tailwind CSS Blog
V
Vulnerabilities – Threatpost
Forbes - Security
Forbes - Security
Apple Machine Learning Research
Apple Machine Learning Research
O
OpenAI News
AWS News Blog
AWS News Blog
月光博客
月光博客

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Calling AmiVoice's Synchronous HTTP API Through a Next.js BFF — Auth, multipart Order, and the WebM Trap
Uya · 2026-06-18 · via DEV Community

Uya

Uya

Posted on • Originally published at zenn.dev

📝 Originally published in Japanese on Zenn. This is the English version.
Canonical: https://zenn.dev/uya0526_design/articles/satellite1_amivoice-bff

📚 This is satellite article #1 in my "Read-Aloud Speed Meter dev log" series. For the whole picture, see the main article.

Where This Sits

In the read-aloud speed meter app, this article covers the part that sends browser-recorded audio to the AmiVoice API to get back recognized text plus timestamps. The theme is calling an external API without exposing your API key to the browser — in other words, implementing a BFF (Backend for Frontend).

The main article only touched the highlights, so here I go down to a level you can reproduce yourself. Specifically, four things:

  • Why you must not call AmiVoice directly from the browser (why a BFF is needed)
  • AmiVoice's synchronous HTTP auth, parameters, and multipart order
  • Why the browser's MediaRecorder output (WebM/Opus) passes through as-is
  • Reshaping the raw JSON with a pure-function mapper and testing it with fixtures

💡 I'm an ex-Java engineer learning TypeScript in public, so I drop in comparisons to Java here and there.


Why a BFF Is Needed

Using the AmiVoice API requires an API key. And that key must never appear in browser-side code. Frontend JavaScript is fully inspectable by the user, so writing the key there leaks it instantly.

So I insert a relay that holds the key.

[Browser] ──audio Blob──▶ [Next.js API Route (BFF / holds key)] ──▶ [AmiVoice API]
 record / display   audio field      reshape into u / d / a        speech → text

The browser only calls my own API Route (/api/recognize), and that Route attaches the key server-side and forwards to AmiVoice. The key is just read from process.env and never ends up in the bundle shipped to the browser.

Java comparison: This is the same as a Spring @RestController reading an external API key from application.yml (env vars) and relaying without showing it to the client. Think "a thin Servlet that hides the secret and relays an external API." In Next.js, the export async function POST in app/api/recognize/route.ts corresponds to @PostMapping.


AmiVoice Synchronous HTTP API Spec

I used the synchronous HTTP interface, implementing against the official manual and double-checking with curl. The key points:

Item Detail
Endpoint POST https://acp-api.amivoice.com/v1/nolog/recognize (no-log version)
Auth Put the API key in the multipart u part (not an Authorization header)
Engine Engine name in d (e.g. -a-general = general conversational)
Audio Binary in a. Must be the final multipart part
Response text at the top; per-word starttime/endtime in results[].tokens[]
Error check code empty string "" = success; code !== "" = failure

I hit three traps here. Let me share them in order.

Trap ① — Auth is the u field, not a header

When I think "REST API auth," I think Authorization: Bearer .... AmiVoice's synchronous HTTP is different: the API key goes in a multipart field called u. My first version put it in a header, got a 401-style failure, and I stalled here.

Trap ② — The audio a goes last

The multipart parts need to be in the order uda (audio), with the audio as the final part. Adding another field after it caused the audio to be ignored. The order you append to FormData carries meaning directly.

Trap ③ — WebM/Opus passes through as-is (c can be omitted)

The browser's MediaRecorder usually outputs audio/webm;codecs=opus. I braced for "I'll probably need to convert the format before handing it to AmiVoice," but WebM + Opus carries a header in the container, so the audio-format parameter c can be omitted on synchronous HTTP (verified with curl). You can send the recording Blob unconverted.


Implementing the API Route (BFF)

Here's app/api/recognize/route.ts with the traps accounted for.

const AMIVOICE_ENDPOINT = "https://acp-api.amivoice.com/v1/nolog/recognize";
const AMIVOICE_ENGINE = "-a-general"; // general conversational

export async function POST(req: Request) {
  // 1. Receive the audio Blob from the browser under the "audio" field
  const inForm = await req.formData();
  const audio = inForm.get("audio") as Blob;

  // 2. Reshape into u / d / a order for AmiVoice
  const outForm = new FormData();
  outForm.append("u", process.env.AMIVOICE_API_KEY ?? ""); // auth (not a header)
  outForm.append("d", AMIVOICE_ENGINE);                    // engine
  outForm.append("a", audio, "recording.webm");            // audio (always last)

  // 3. Forward to synchronous HTTP and return the raw JSON as-is
  const res = await fetch(AMIVOICE_ENDPOINT, { method: "POST", body: outForm });
  const body = await res.text();
  return new NextResponse(body, {
    status: res.status,
    headers: { "Content-Type": res.headers.get("Content-Type") ?? "application/json" },
  });
}

(Simplified. In the real code, a missing AMIVOICE_API_KEY returns 500 and never sends an empty key to AmiVoice.)

The key idea is "two stages of FormData." Browser → my Route receives under the audio field; Route → AmiVoice reassembles into u/d/a.

Java comparison: It's the same shape as reshaping an inbound DTO into the multipart form for an outbound external API. "The shape you receive and the shape you send are different things" maps directly onto the FormData reshape.

I designed this Route to return AmiVoice's raw JSON almost untouched. Rather than putting formatting in the Route, I leave it to the next mapper (a pure function), separating responsibilities.

Look at the raw JSON with curl first

Before implementing, hitting the endpoint with curl to see the shape of the raw response turned out to be the fastest route in the end.

curl -X POST https://acp-api.amivoice.com/v1/nolog/recognize \
  -F u="$AMIVOICE_API_KEY" \
  -F d="-a-general" \
  -F a=@recording.webm

I pass the API key from an environment variable ($AMIVOICE_API_KEY) so I never hardcode a raw key in command history or code. "Keep the key out of the code" applies from the curl-verification stage onward.

The returned JSON looks roughly like this (excerpted; values are examples):

{
  "results": [
    {
      "tokens": [
        { "written": "一番", "spoken": "いちばん", "starttime": 1080, "endtime": 1480 },
        { "written": "買っ", "spoken": "かっ", "starttime": 1480, "endtime": 1672 },
        { "written": "た", "spoken": "た", "starttime": 1720, "endtime": 1800 }
      ],
      "text": "一番買った"
    }
  ],
  "text": "一番買った",
  "code": ""
}


The Mapper: Raw JSON → App Type (a Pure Function)

I reshape the raw JSON into the AmiVoiceResponse type used inside the app. I make this conversion a pure function with no I/O, sitting as a layer outside the measurement logic (calculateMetrics).

interface AmiVoiceResponse {
  text: string;
  segments: { starttime: number; endtime: number }[];
}

export function mapAmiVoiceResponse(rawResponse: unknown): AmiVoiceResponse {
  if (typeof rawResponse !== "object" || rawResponse === null) {
    throw new Error("Invalid response");
  }
  const { text, results } = rawResponse as {
    text: string;
    results: { tokens: { starttime: number; endtime: number }[] }[];
  };
  const segments = results[0]?.tokens.map((token) => ({
    starttime: token.starttime ?? 0,
    endtime: token.endtime ?? 0,
  })) ?? [];
  return { text, segments };
}

There was one fix here too. My first version referenced raw.result.tokens (singular) and got nothing back; I corrected it to raw.results[0].tokens (a plural array). It's a mistake I could have prevented by looking at the raw JSON with curl first, and it reaffirmed how important it is to "get hold of real data early."

🧭 Design decision: You can build segments "per word" or "per utterance." I went with per word, because the gaps (silence) between words then feed into the stagnation rate, letting me measure fluency more granularly.


Testing With Fixtures

Since the mapper is a pure function, it's straightforward to test with Vitest. The key is to save the real data captured with curl as a fixture.

fixtures/
├── test_01.json   # short response (3 tokens)
└── test_02.json   # based on real curl data (9 tokens)

import { describe, test, expect } from "vitest";
import { mapAmiVoiceResponse } from "./mapAmiVoiceResponse";
import raw01 from "../../fixtures/test_01.json";

describe("mapAmiVoiceResponse", () => {
  test("builds segments from tokens and extracts text", () => {
    const result = mapAmiVoiceResponse(raw01);
    expect(result.segments).toHaveLength(3);
    // Not just "the shape matches" — pin the concrete values
    expect(result.segments[0].starttime).toBe(1080);
    expect(result.segments[0].endtime).toBe(1480);
    expect(result.text).toBe("一番買った");
  });
});

What I was conscious of here is a lesson from a past project: "a passing test ≠ behaving as intended." If you only compare the result of .map() against another .map(), you end up writing the test with the same logic as the mapper, which doesn't verify intent. So by hardcoding concrete values like starttime: 1080 and asserting on them, I locked down "is it really pulling the correct values?"

Java comparison: Fixtures are like JUnit test resources (JSON under src/test/resources); toHaveLength / concrete-value asserts correspond to assertEquals. The idea of "pinning production-like raw JSON into your tests" carried over directly.


What I Implemented Myself / What I Asked AI For

This is AI-collaborative development, so for transparency I write out the split.

Area Detail
My decisions / implementation Adopting the BFF structure, the u/d/a order, the raw-JSON-return policy, choosing per-word segments, concrete-value asserts in fixtures, checking the official manual, curl verification
Asked AI for The POST handler skeleton, fetch / FormData boilerplate, a first-draft mapper example, examples of how to write the tests
Fixed on AI's pointer resultresults[0], Authorization header → u field, a weak .map()-only test → concrete-value asserts

AI provided boilerplate examples, but the rewrites to match the official spec, the verification, and the fixes were all mine.


Wrapping Up

This was my record of calling AmiVoice's synchronous HTTP API through a Next.js BFF. The takeaways:

  1. Keep the API key out of the browser. Use a BFF that relays through Next.js API Routes.
  2. For synchronous HTTP, auth is the u field, the audio a is the final part, and WebM/Opus lets you omit c.
  3. Reshape the raw JSON with a pure-function mapper, and test it with a fixture of real curl data + concrete-value asserts.

Most of my stumbles were ones I could have prevented by looking at the raw response first. When working with an external API, hit it once with curl and look at the raw JSON with your own eyes before implementing — that order turned out to be the fastest.

The detailed development log is in the repository's LEARNING_LOG_Phase1_Step3.md.

Next time I cover the "two-stage" design that hands the recognized result (settled facts) to Claude Haiku to generate one-line feedback → satellite #2, "Claude Haiku coaching design and the prompt swamp" ({{DEVTO_SATELLITE_2_URL}}).


This article is part of my public learning journey using AI tools (Claude / Cursor). The design, tech selection, and implementation decisions are mine, and the code is verified with Vitest. I collaborate with AI on the article's structure, outline, and draft prose, and I review and revise every line before publishing.