Returning JSON objects from an Azure Function in Node.js & Typescript
13 July, 2021
By default, a new Javascript/Typescript function created in an Azure functions app stringifies any data the function returns in the context.res object. This is because the default content-type header is text for all node.js functions in Azure.
The context.res object is generated by the Azure function runtime as a wrapper around the node runtime's default response object and contains all the information that is sent back to the client after the function executes.
Most of the data transfers do not require the data to be in a string format.
Simply adding this to the beginning of the specific function will always return the JSON object format instead:
context.res.headers = { "Content-Type": "application/json" };
This forces the response header to the http request to have the json content type for the data.
So instead of having a response like this:
context.res.body = '{"success": "true", "message":"Function ran successfully"}';
You will end up with:
context.res.body = { success: true, message: "Function ran successfully" };
If you liked this post, please share it!