import { type NextRequest, NextResponse } from "next/server"; import { backendUrl } from "@/lib/backend-url"; // Stream multipart uploads to FastAPI. Calling request.formData() here buffers // the whole PDF in Next.js and can fail before the backend sees the file. export const dynamic = "force-dynamic"; export const runtime = "nodejs"; export async function POST(request: NextRequest) { const backend = backendUrl(); const headers = new Headers(); const requestContentType = request.headers.get("content-type"); const requestContentLength = request.headers.get("content-length"); const cookie = request.headers.get("cookie"); console.info("[upload proxy] received upload request", { contentType: requestContentType, contentLength: requestContentLength, hasBody: Boolean(request.body), }); if (!requestContentType?.includes("multipart/form-data")) { return NextResponse.json( { detail: `Upload request must be multipart/form-data; received ${requestContentType ?? "no content-type"}.`, }, { status: 400 } ); } if (requestContentType) headers.set("content-type", requestContentType); if (cookie) headers.set("cookie", cookie); if (!request.body) { return NextResponse.json({ detail: "Upload request did not include a file body." }, { status: 400 }); } let response: Response; try { response = await fetch(`${backend}/upload`, { method: "POST", body: request.body, duplex: "half", headers, } as RequestInit & { duplex: "half" }); } catch (error) { return NextResponse.json( { detail: `Could not reach the backend upload service: ${(error as Error).message}` }, { status: 502 } ); } const contentType = response.headers.get("content-type") ?? "text/plain; charset=utf-8"; const body = await response.text(); return new NextResponse(body, { status: response.status, headers: { "content-type": contentType }, }); }