Hono: Send a response to the client

In the Hello World example we used the c.text() method to send a simple string as a response, and to close the connection:

(c) => c.text('Hello, World!')

This sets the Content-Type header to text/html, and sends the string passed in as parameter.

After this, Hono closes the connection.

You can use c.json() to parse an object or array into JSON and set the application/json Content-Type header.

app.get('/', (c) => c.json({ test: true }))

Using c.html() you can pass an HTML string and that’s sent using the Content-Type header text/html.

app.get('/', (c) => {
  c.html(`
    <html>
      <head>
        <title>test</title>
      </head>
      <body>
        <h1>test</h1>
        <p>test</p>
      </body>
    </html>
  `)
})

The browser will correctly render the HTML:

Since we used a template literal (using backticks), we can also interpolate data:

app.get('/', (c) => {
  const numbers = ['one', 'two', 'three']

  return c.html(`
    <html>
      <head>
        <title>test</title>
      </head>
      <body>
        <h1>test</h1>
        ${numbers.map((num) => '<p>' + num + '</p>').join('\n')}
      </body>
    </html>
  `)
})

Anyway we’ll see a better way of creating HTML later when I’ll show you how to use JSX in Hono.

Set the HTTP response status

You can return a 404 response by returning c.notFound().

Otherwise you use c.status() passing 404: c.status(404)

Lessons in this unit:

0: Introduction
1: Your first Hono app
2: The Request object
3: ▶︎ Send a response to the client
4: Manage cookies
5: Work with HTTP headers
6: Handling redirects
7: Routing
8: JSX templates
9: Middleware
10: Hono on Node.js
11: Handling forms COMING SOON
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!