# Return JSON

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.

```js
  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`, 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](/en/documentation/devtools/runtime/node/events/#async-event-handlers).

## Related resources

- [JavaScript examples](/en/documentation/platform/functions/javascript-examples.md): Browse the rest of the snippets in this collection.
- [FetchEvent](/en/documentation/devtools/runtime/api-reference/fetch-event.md): Read the reference for the event this handler listens to, including `respondWith()`.
- [Response](/en/documentation/devtools/runtime/api-reference/response.md): Check the status, headers, and body options the constructor accepts.
- [How Functions works](/en/documentation/platform/functions/how-it-works.md): See what has to exist before a function runs on a request.
- [Functions limits](/en/documentation/platform/functions/limits.md): The ceilings a single invocation of this function runs inside, and the ones that vary by plan.
- [Query usage data from Functions](/en/documentation/guides/platform/observability/query-functions-usage-data-with-graphql.md): Read back the compute time and the invocations this function has consumed.
