Uploading base64 images to Sanity and resolving a 400 error
Yes, you can upload base64 images to Sanity, but you need to convert the base64 string first. The client.assets.upload() method accepts File | Blob | Buffer | NodeStream, but not raw base64 strings directly.
Here's what you need to do:
1. Strip the data URI prefix
If your base64 string includes the data URI header (like data:image/jpeg;base64,), you need to remove it first. This header often causes the "Invalid image, could not read metadata" error.
2. Convert to Buffer
Convert the base64 string to a Buffer:
const base64Data = imageBase64.replace(/^data:image\/\w+;base64,/, '');
const uploadBuffer = Buffer.from(base64Data, 'base64');
await client.assets.upload('image', uploadBuffer, {
contentType: 'image/jpeg', // or whatever your image type is
filename: 'myimage.jpg'
});Alternative: Use a blob utility
You can also use a package like blob-util to convert base64 to a Blob, which several developers in the Sanity community have found helpful for this exact use case.
The key issue is that Sanity's asset pipeline needs to read the image metadata to process it, and it can only do that from actual binary data (Buffer/Blob), not from a base64-encoded string. Once you convert it properly, the upload should work fine.
For reference, according to the Sanity documentation on images, Sanity supports JPEG, PNG, and WebP as processed output formats, with GIF and SVG passing through untouched. Make sure your contentType option in the upload method matches your actual image format.
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.