{"record":{"id":"755248ecb79612a7","repo":"danny-avila/LibreChat","slug":"remote-file-response-too-large-buffer-length-b-755248","errorCode":null,"errorMessage":"Remote file response too large: ${buffer.length} bytes","messagePattern":"Remote file response too large: (.+?) bytes","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"api/server/services/Files/Local/crud.js","lineNumber":136,"sourceCode":" *\n * @returns {Promise<{ bytes: number, type: string, dimensions: Record<string, number>} | null>}\n *          A promise that resolves to the file metadata if the file is successfully saved, or null if there is an error.\n */\nasync function saveFileFromURL({ userId, URL, fileName, basePath = 'images' }) {\n  try {\n    const maxBytes = getRemoteFileFetchMaxBytes();\n    const response = await axios({\n      url: assertRemoteFileURL(URL),\n      responseType: 'arraybuffer',\n      timeout: getRemoteFileFetchTimeoutMs(),\n      maxContentLength: maxBytes,\n      maxBodyLength: maxBytes,\n    });\n    assertRemoteFileContentLength(response.headers, maxBytes);\n\n    const buffer = Buffer.from(response.data, 'binary');\n    if (buffer.length > maxBytes) {\n      throw new Error(`Remote file response too large: ${buffer.length} bytes`);\n    }\n\n    const { bytes, type, dimensions, extension } = await getBufferMetadata(buffer);\n\n    // Construct the outputPath based on the basePath and userId\n    const outputPath = path.join(paths.publicPath, basePath, userId.toString());\n\n    // Check if the output directory exists, if not, create it\n    if (!fs.existsSync(outputPath)) {\n      fs.mkdirSync(outputPath, { recursive: true });\n    }\n\n    // Replace or append the correct extension\n    const extRegExp = new RegExp(path.extname(fileName) + '$');\n    fileName = fileName.replace(extRegExp, `.${extension}`);\n    if (!path.extname(fileName)) {\n      fileName += `.${extension}`;\n    }","sourceCodeStart":118,"sourceCodeEnd":154,"githubUrl":"https://github.com/danny-avila/LibreChat/blob/5ff282f9006c436e561de1afd39a481bea1ef0d8/api/server/services/Files/Local/crud.js#L118-L154","documentation":"Thrown by saveFileFromURL after downloading a remote file via axios when the resulting buffer exceeds REMOTE_FILE_FETCH_MAX_BYTES (default 512 MB). Despite axios being configured with maxContentLength and maxBodyLength, this check fires as a post-download defense-in-depth guard for cases where the remote server serves a larger body than its Content-Length header advertised or omits the header entirely. Note: this error is caught internally and the function returns null (does not propagate).","triggerScenarios":"Calling saveFileFromURL({ userId, URL, fileName }) where the remote host serves a file body larger than the configured max. This fires when the fully buffered response exceeds maxBytes even after axios's own maxContentLength guard and the assertRemoteFileContentLength header check.","commonSituations":"A user provides a URL to a very large file. The remote CDN uses chunked transfer encoding with no Content-Length, so axios's maxContentLength check is bypassed. Or REMOTE_FILE_FETCH_MAX_BYTES was lowered to a restrictive value. Since saveFileFromURL catches this and returns null, the caller sees a null result rather than an exception.","solutions":["Verify the source URL points to the intended file and not a larger resource (e.g., a full album ZIP instead of a single image).","If larger files are legitimate, raise REMOTE_FILE_FETCH_MAX_BYTES in your .env.","Pre-check file size with a HEAD request before calling saveFileFromURL.","Handle the null return value from saveFileFromURL gracefully in the calling code, surfacing a clear user-facing error."],"exampleFix":"// before\nconst result = await saveFileFromURL({ userId, URL, fileName });\n\n// after — handle null return (the error is swallowed internally)\nconst result = await saveFileFromURL({ userId, URL, fileName });\nif (!result) {\n  throw new Error('File could not be saved from URL. It may exceed the maximum allowed size.');\n}","handlingStrategy":"validation","validationCode":"const maxBytes = getRemoteFileFetchMaxBytes();\nconst head = await axios.head(assertRemoteFileURL(URL), { timeout: 5000 });\nconst contentLength = parseInt(head.headers['content-length'] ?? '0', 10);\nif (contentLength > maxBytes) {\n  throw new Error(`File exceeds maximum size of ${maxBytes} bytes`);\n}","typeGuard":null,"tryCatchPattern":"const result = await saveFileFromURL({ userId, URL, fileName });\nif (!result) {\n  // saveFileFromURL catches errors internally and returns null\n  throw new Error('Failed to save file from URL — it may exceed the size limit');\n}","preventionTips":["Pre-check file size with a HEAD request before downloading.","Set REMOTE_FILE_FETCH_MAX_BYTES to match your application's real limits.","Always handle the null return from saveFileFromURL — its internal catch swallows errors."],"tags":["file-upload","local-storage","size-limit","network","defense-in-depth"],"backgroundTag":null,"analyzedSha":"5ff282f9006c436e561de1afd39a481bea1ef0d8","analyzedAt":"2026-08-12T21:38:08.145Z","schemaVersion":2},"datasetVersion":"2026-08-12T23:17:12.415Z"}