diff --git a/src/app/api/ask-ai/route.ts b/src/app/api/ask-ai/route.ts index d16dfb5..d4d606f 100644 --- a/src/app/api/ask-ai/route.ts +++ b/src/app/api/ask-ai/route.ts @@ -198,8 +198,24 @@ async function callGroqWithFallback( /** * Main AI Solver API Route. */ +// Maximum allowed Content-Length for this route in bytes. +// imageBase64 payloads are read entirely into memory before the slice, so a +// large body allocates the full payload on the server heap before any truncation +// occurs. Enforcing this limit early keeps memory usage predictable under load. +const MAX_BODY_BYTES = 512 * 1024; // 512 KB + export async function POST(req: Request) { try { + // Reject oversized payloads before parsing JSON to avoid loading + // a multi-megabyte body into memory only to discard most of it. + const contentLength = parseInt(req.headers.get('content-length') ?? '0', 10); + if (contentLength > MAX_BODY_BYTES) { + return NextResponse.json( + { error: 'Request payload too large. Maximum size is 512 KB.' }, + { status: 413 } + ); + } + const user = await currentUser(); if (!user) {