Return a blob from a serverless function

I have a serverless function that makes an API call to an API that returns a blob object that is an image but when I try to return the blob to my frontend code, the blob turns into a default javascript object and I cant create its object url, this is the code Im using to return the blob:

exports.handler = async(event) => {
    const request = await fetch(
        "https://api-example.com",
        {
            headers: { Authorization: "Bearer MyApiKey" },
            method: "POST",
            body: JSON.stringify({ inputs: event.queryStringParameters.input }),
        }
    );
    const response = await request.blob();
    return {
        statusCode: 200,
        body: JSON.stringify({blobObj: response})
    }
}

and in my frontend code i have this:

async function query(data) {
  const response = await fetch(
		"/.netlify/functions/StableDiffusionReq?input=" + data,
		{
			method: "GET",
		}
	);
  const result = await response.json();
	return result.blobObj;
}

but the object I get is not a blob, my website domain is: falconchatbot.netlify.app

I don’t believe you can JSON.stringify() a blob. I believe you instead need to serve a base64 string: get-random-image.js (github.com). Do note, the limit is 6 MB and base64 usually increases the size by about 1.37 times.

1 Like