Files
breakpilot-lehrer/studio-v2/app/api/vocabulary/[...path]/route.ts
T
Benjamin Admin 6b3bff48f0 Fix: Proxy uses arrayBuffer for audio/image responses (not text)
Binary data (MP3 audio) was corrupted by resp.text(). Now detects
content-type and uses arrayBuffer() for audio/* and image/* responses.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-26 23:33:57 +02:00

48 lines
1.5 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-lehrer:8001'
async function proxyRequest(
request: NextRequest,
{ params }: { params: Promise<{ path: string[] }> }
): Promise<NextResponse> {
const { path } = await params
const pathStr = path.join('/')
const searchParams = request.nextUrl.searchParams.toString()
const url = `${BACKEND_URL}/api/vocabulary/${pathStr}${searchParams ? `?${searchParams}` : ''}`
try {
const fetchOptions: RequestInit = {
method: request.method,
headers: { 'Content-Type': 'application/json' },
}
if (request.method !== 'GET' && request.method !== 'HEAD') {
fetchOptions.body = await request.text()
}
const resp = await fetch(url, fetchOptions)
const contentType = resp.headers.get('Content-Type') || 'application/json'
// Binary responses (audio, images) must use arrayBuffer, not text
if (contentType.startsWith('audio') || contentType.startsWith('image')) {
const buffer = await resp.arrayBuffer()
return new NextResponse(buffer, {
status: resp.status,
headers: { 'Content-Type': contentType },
})
}
const data = await resp.text()
return new NextResponse(data, {
status: resp.status,
headers: { 'Content-Type': contentType },
})
} catch (e) {
return NextResponse.json({ error: String(e) }, { status: 502 })
}
}
export const GET = proxyRequest
export const POST = proxyRequest
export const PUT = proxyRequest
export const DELETE = proxyRequest