Return array buffer
How can i return an
ArrayBuffer in a server handler (nitro)?
The response is always an empty json object if i try to return an array buffer.2 Replies
Hi @Luex. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
To return an ArrayBuffer from a server handler in Nitro (Nuxt), you should not return the ArrayBuffer directly as the handler's return value, because Nitro (and h3) will serialize the return value as JSON by default, resulting in an empty object or incorrect response.
Instead, you should use the h3 utility function sendStream or set the response headers and body manually to send binary data. While the knowledge sources do not provide a direct example for ArrayBuffer, they do show how to return raw binary data using storage and custom server routes. For example, when serving files from storage, the handler returns the raw data (such as a Buffer or Uint8Array) directly, which Nitro will send as the response body with the correct content type if you set it appropriately:
If you specifically want to return an ArrayBuffer, ensure your storage driver supports returning it (for example, with Cloudflare R2 you can use
{ type: "arrayBuffer" } as an option to getItemRaw). Then, return the ArrayBuffer as shown above. Nitro will send the binary data as the response body if you set the appropriate headers and do not attempt to JSON-serialize the response.
Key points:
- Do not return the ArrayBuffer as a JSON object.
- Set the correct Content-Type header (e.g., application/octet-stream).
- Return the raw data directly from the handler.
For more details on using getItemRaw and returning binary data, see the storage and unstorage documentation examples in the knowledge sources:
- Unstorage interface: getItemRaw
- Serving files with useStorage in Nuxt/Nitro
- Cloudflare R2 driver: getItemRaw with type "arrayBuffer"
If you still get an empty object, double-check that you are not returning the ArrayBuffer inside an object (e.g., { data: arrayBuffer }), as this will be serialized as JSON. Return the ArrayBuffer directly.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@1355686004618428456> Kapa.ai is still learning and improving, please let me know how I did by reacting below.