Deno LandDeno

Deploy Docs

Return JSON/HTML

Deploy this example

We're often required to respond with different types of content to requests. JSON and HTML are most common type of content that's transmitted between clients and servers.

function handleRequest(request) {
  const { pathname } = new URL(request.url);

  // Respond with HTML
  if (pathname.startsWith("/html")) {
    const html = `<html>
      <p><b>Message:</b> Hello from Deno Deploy.</p>
      </html>`;

    return new Response(html, {
      headers: {
        // The "text/html" part implies to the client that the content is HTML
        // and the "charset=UTF-8" part implies to the client that the content
        // is encoded using UTF-8.
        "content-type": "text/html; charset=UTF-8",
      },
    });
  }

  // Respond with JSON
  if (pathname.startsWith("/json")) {
    // Use stringify function to convert javascript object to JSON string.
    const json = JSON.stringify({
      message: "Hello from Deno Deploy",
    });

    return new Response(json, {
      headers: {
        "content-type": "application/json; charset=UTF-8",
      },
    });
  }
}

addEventListener("fetch", (event) => {
  event.respondWith(handleRequest(event.request));
});

The interpretation of the body of the response by the client depends on the content-type header. That's the reason we have different values for HTML and JSON in the content-type header in the above examples. You can learn more about the common values that are accepted by the content-type header to return content other than HTML and JSON.


Please file an issue in our feedback repository if you find any problem in Deploy service or documentation.