{"record":{"id":"0bfb0826db1e2739","repo":"danny-avila/LibreChat","slug":"failed-to-convert-base64-to-buffer-error-messag","errorCode":null,"errorMessage":"Failed to convert base64 to buffer: ${error.message}","messagePattern":"Failed to convert base64 to buffer: (.+?)","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"api/server/services/Files/process.js","lineNumber":1251,"sourceCode":" * @returns {Buffer<ArrayBufferLike>}\n */\nfunction base64ToBuffer(base64String) {\n  try {\n    const typeMatch = base64String.match(/^data:([A-Za-z-+/]+);base64,/);\n    const type = typeMatch ? typeMatch[1] : '';\n\n    const base64Data = base64String.replace(/^data:([A-Za-z-+/]+);base64,/, '');\n\n    if (!base64Data) {\n      throw new Error('Invalid base64 string');\n    }\n\n    return {\n      buffer: Buffer.from(base64Data, 'base64'),\n      type,\n    };\n  } catch (error) {\n    throw new Error(`Failed to convert base64 to buffer: ${error.message}`);\n  }\n}\n\nasync function saveBase64Image(\n  url,\n  { req, file_id: _file_id, filename: _filename, endpoint, context, resolution },\n) {\n  const appConfig = req.config;\n  const effectiveResolution = resolution ?? appConfig.fileConfig?.imageGeneration ?? 'high';\n  const file_id = _file_id ?? v4();\n  let filename = `${file_id}-${_filename}`;\n  const { buffer: inputBuffer, type } = base64ToBuffer(url);\n  if (!path.extname(_filename)) {\n    const extension = mime.getExtension(type);\n    if (extension) {\n      filename += `.${extension}`;\n    } else {\n      throw new Error(`Could not determine file extension from MIME type: ${type}`);","sourceCodeStart":1233,"sourceCodeEnd":1269,"githubUrl":"https://github.com/danny-avila/LibreChat/blob/5ff282f9006c436e561de1afd39a481bea1ef0d8/api/server/services/Files/process.js#L1233-L1269","documentation":"Outer wrapper thrown by base64ToBuffer's catch when any error inside the try escapes — including the explicit 'Invalid base64 string' throw (error 137) or an unexpected exception during regex match or Buffer.from. The wrapper prefixes the message so callers always see a consistent 'Failed to convert base64 to buffer:' shape. The underlying cause is in the interpolated `error.message`.","triggerScenarios":"Any exception inside base64ToBuffer: the inner 'Invalid base64 string' throw, a malformed input causing `Buffer.from` to throw on invalid base64 characters, or an unlikely regex engine error. In practice most cases are the empty-payload case (which surfaces as '...Invalid base64 string') or non-base64 characters in the body.","commonSituations":"Caller passes a string with characters outside the base64 alphabet (whitespace, unicode, control chars); URL-encoded data URL whose `+`/`/` were mangled; truncated payload; the empty-payload case from error 137 bubbled through this wrapper.","solutions":["Inspect the trailing `: <reason>` — 'Invalid base64 string' means empty after prefix (see error 137); other text indicates a Buffer.from failure.","Sanitize the input: strip whitespace/newlines and confirm the body matches `^[A-Za-z0-9+/]+=*$`.","Re-encode the source via `Buffer.from(buf).toString('base64')` to guarantee a clean alphabet.","Avoid passing URL-decoded payloads — preserve `+` and `/` and the trailing `=` padding."],"exampleFix":"// before\nconst clean = raw.replace(/\\s/g, ''); // partial fix, still allows bad chars\n\n// after\nconst body = raw.replace(/^data:[^;]+;base64,/, '').replace(/\\s/g, '');\nif (!/^[A-Za-z0-9+/]*={0,2}$/.test(body)) throw new Error('Not valid base64');\nconst { buffer } = base64ToBuffer(`data:${mime};base64,${body}`);","handlingStrategy":"validation","validationCode":"function sanitizeBase64(raw) {\n  const body = raw.replace(/^data:[^;]+;base64,/, '').replace(/\\s/g, '');\n  if (!/^[A-Za-z0-9+/]*={0,2}$/.test(body)) {\n    throw new Error('Invalid base64 characters');\n  }\n  return body;\n}","typeGuard":null,"tryCatchPattern":"try { base64ToBuffer(s); }\ncatch (e) {\n  if (/Failed to convert base64 to buffer/.test(e.message)) {\n    return res.status(400).json({ error: 'Malformed image data; please re-upload.' });\n  }\n  throw e;\n}","preventionTips":["Strip whitespace/newlines from base64 before sending.","Preserve `+`, `/`, and trailing `=` padding — don't URL-decode the body.","Inspect the trailing reason text to distinguish empty vs invalid-character cases."],"tags":["base64","wrapper-error","input-validation"],"backgroundTag":null,"analyzedSha":"5ff282f9006c436e561de1afd39a481bea1ef0d8","analyzedAt":"2026-08-12T21:38:08.145Z","schemaVersion":2},"datasetVersion":"2026-08-12T23:17:12.415Z"}