Return JSON
Serialize an object and return it as a JSON response with the correct content-type header, for lightweight APIs and middleware.
Return a JSON payload directly from a function, without forwarding the request to an origin. Use this pattern for lightweight APIs and middleware, such as API mocks, feature flags, configuration endpoints, and health checks, where the response is structured data and no backend service has to be involved.
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, which tells the client the payload is JSON. event.respondWith() returns the response, with no request to an origin.
The same shape covers richer responses. Set a status code or add CORS and cache-control headers in the second argument to Response, and build the object from request data, such as query string parameters, cookies, or headers, instead of hardcoding it.
The object can also be assembled from data the function fetches. A handler that calls fetch() for each of several URLs, parses each response with response.json(), and awaits them together with Promise.all() returns one JSON body built from all of them. For a worked example, refer to Example: Async event handlers.