JavaScript Examples - Return JSON
Return a JSON payload directly from a function. Use this pattern to build lightweight APIs or middleware that respond on Azion’s global network, serving structured data to clients without forwarding the request to an origin. It’s a common building block for API mocks, feature flags, configuration endpoints, and health checks, where you need a fast, predictable, structured response without standing up a dedicated backend service.
addEventListener("fetch", event => { const data = { hello: "world" }
const json = JSON.stringify(data, null, 2)
return event.respondWith( new Response(json, { headers: { "content-type": "application/json;charset=UTF-8" } }) ) })How it works
When the fetch event fires, the handler defines a plain JavaScript object and serializes it with JSON.stringify(data, null, 2), where the 2 adds indentation so the output is easy to read. It then creates a new Response with that string as the body and sets the content-type header to application/json;charset=UTF-8, signaling to clients that the payload is JSON. Finally, event.respondWith() returns the response, delivering the data with low latency and without contacting an origin. You can extend this pattern by setting a custom status code, adding CORS or cache-control headers, or building the object dynamically from request data such as query string parameters, cookies, or headers, all while keeping the response close to your users. Because the function runs on Azion’s distributed network, the same logic scales automatically to absorb traffic spikes without any additional configuration or server management.