Skip to content

Routing Fundamentals

Routing is the mechanism by which requests are directed to the code that handles them. In Hono.js, routing is intuitive and follows standard HTTP patterns.

HTTP verbs (also called methods) are actions that tell the server what to do with a resource. Think of them like commands in a game. Here are the most common ones you’ll use:

  • GET: Retrieve or read data. Like asking “What’s the weather today?” – you get information without changing anything.
  • POST: Create something new. Like posting a letter – you send data to add to the server.
  • PUT: Update or replace something completely. Like rewriting a whole story – you replace the existing data.
  • PATCH: Update part of something. Like fixing a small error – you modify only what’s needed.
  • DELETE: Remove something. Like deleting a file – you take it away from the server.

In Hono, each verb has a method like app.get(), app.post(), etc. You’ll use these to build your API endpoints.

Hono provides methods for all standard HTTP verbs: get, post, put, patch, delete.

import { Hono } from "hono";
const app = new Hono();
// GET request to the root
app.get("/", (c) => c.text("Hello Hono!"));
// POST request to create a resource
app.post("/tasks", (c) => c.json({ message: "Task created" }));
// DELETE request to remove a resource
app.delete("/tasks", (c) => c.json({ message: "Task deleted" }));
export default app;

Route parameters are named segments of the URL, specified by a colon :. They are used to capture values at specific positions in the URL.

app.get("/tasks/:id", (c) => {
const id = c.req.param("id");
return c.text(`Fetching task with ID: ${id}`);
});

If you visit /tasks/123, the response will be Fetching task with ID: 123.

Query parameters are key-value pairs at the end of a URL (e.g., /search?q=hono).

app.get("/search", (c) => {
const query = c.req.query("q");
return c.text(`Searching for: ${query}`);
});

In modern API development, we almost always communicate using JSON. Hono makes this easy with c.json().

app.get("/api/status", (c) => {
return c.json({
status: "ok",
timestamp: new Date(),
});
});

As your application grows, you might want to group related routes. Hono supports this via chaining or sub-apps, but for now, we’ll keep it simple.

In the next section, we’ll look at how to add functionality that runs before your route handlers using Middleware.

  1. Which HTTP method is used to create a new resource?

    Answer POST

  2. How do you access the value of id in the route /tasks/:id?

    Answer c.req.param("id")

  3. True or False: c.json() automatically sets the Content-Type header to application/json.

    Answer True