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
Want to learn more? Check out our courses