Routes and HTTP methods
A route is a rule "method + address → function". When a request arrives, Hono looks for a route with a matching method and address and calls its handler. If there is no such route, Hono answers with a 404 code itself.
A simple route
Routes are added in src/index.ts, before the serve() call:
// src/index.ts
app.get('/about', (c) => c.text('A blog about programming'))Open http://localhost:3000/about and the page shows "A blog about programming". The address /contacts returns the text 404 Not Found.
HTTP methods
Every HTTP method has its own app method. One address can answer differently to different methods:
// src/index.ts
app.get('/posts', (c) => c.text('List of posts'))
app.post('/posts', (c) => c.text('Post created', 201))
app.put('/posts/1', (c) => c.text('Post 1 replaced'))
app.patch('/posts/1', (c) => c.text('Post 1 partly updated'))
app.delete('/posts/1', (c) => c.text('Post 1 deleted'))The second argument of c.text() is the status code. A browser following a link always sends GET, so check the other methods with curl:
curl -X POST http://localhost:3000/posts
curl -X DELETE http://localhost:3000/posts/1The terminal prints "Post created" and "Post 1 deleted".
| Method | Used to |
|---|---|
GET | read data |
POST | create a record |
PUT | replace a whole record |
PATCH | change some fields |
DELETE | delete a record |
Several methods at once
app.all() matches any method, and app.on() takes a list of methods:
// src/index.ts
app.on(['PUT', 'PATCH'], '/posts/2', (c) => c.text('Post 2 updated'))
app.all('/ping', (c) => c.text('pong'))/ping answers "pong" to GET, POST and any other method.
Chaining
Route methods return the app, so routes for one address can be written as a chain:
// src/index.ts
app
.get('/comments', (c) => c.text('All comments'))
.post('/comments', (c) => c.text('Comment added', 201))Later, in the lesson on the RPC client, this style is needed to pass types along.
The asterisk
The * character matches any rest of the address:
// src/index.ts
app.get('/files/*', (c) => c.text('Some file'))Both /files/a.txt and /files/docs/b.pdf match.
Common mistake
Hono checks routes in the order they were added. Once a route has returned a response, later routes are not called for that request:
// src/index.ts
app.get('/posts/*', (c) => c.text('Some post'))
app.get('/posts/new', (c) => c.text('New post')) // never runsPut specific addresses above general ones.