Skip to content

Instantly share code, notes, and snippets.

@jldec
Created August 16, 2024 11:51
Show Gist options
  • Save jldec/3ee3a3e0dd6332688572a6a40eb1e46f to your computer and use it in GitHub Desktop.
Save jldec/3ee3a3e0dd6332688572a6a40eb1e46f to your computer and use it in GitHub Desktop.
Example of Response.json() static method
export default {
async fetch(request) {
return Response.json({
date: Date(),
headers: Object.fromEntries(request.headers),
cf: request.cf
});
},
};
@jldec
Copy link
Author

jldec commented Aug 16, 2024

Response: json() static method

People commonly call <response>.json() instance method to parse a json response body of a fetch() request.

But did you know that there is also a Response.json(data, [options]) static method which returns a new Response with your json-stringified data, and adds the content-type: application/json header?

For more details, see https://developer.mozilla.org/en-US/docs/Web/API/Response/json_static

Try it out yourself in the Cloudflare workers sandbox

Worker deployed to https://json.jldec.workers.dev/

Screenshot 2024-08-16 at 13 03 15

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment