0
0
mirror of https://github.com/honojs/hono.git synced 2024-11-21 18:18:57 +01:00
hono/README.md

813 lines
19 KiB
Markdown
Raw Normal View History

<div align="center">
<a href="https://github.com/honojs/hono">
<img src="https://raw.githubusercontent.com/honojs/hono/master/docs/images/hono-title.png" width="500" height="auto" alt="Hono"/>
</a>
</div>
<hr />
2021-12-14 21:17:56 +01:00
[![GitHub Workflow Status](https://img.shields.io/github/workflow/status/honojs/hono/ci)](https://github.com/honojs/hono/actions)
[![GitHub](https://img.shields.io/github/license/honojs/hono)](https://github.com/honojs/hono/blob/master/LICENSE)
2022-02-21 16:01:31 +01:00
[![npm](https://img.shields.io/npm/v/hono)](https://www.npmjs.com/package/hono)
2022-02-23 03:20:29 +01:00
[![npm](https://img.shields.io/npm/dm/hono)](https://www.npmjs.com/package/hono)
2022-02-21 16:01:31 +01:00
[![npm type definitions](https://img.shields.io/npm/types/hono)](https://www.npmjs.com/package/hono)
[![GitHub commit activity](https://img.shields.io/github/commit-activity/m/honojs/hono)](https://github.com/honojs/hono/pulse)
[![GitHub last commit](https://img.shields.io/github/last-commit/honojs/hono)](https://github.com/honojs/hono/commits/master)
2022-07-02 14:48:32 +02:00
[![Deno badge](https://img.shields.io/endpoint?url=https%3A%2F%2Fdeno-visualizer.danopia.net%2Fshields%2Flatest-version%2Fx%2Fhono%2Fmod.ts)](https://doc.deno.land/https/deno.land/x/hono/mod.ts)
2022-02-21 16:01:31 +01:00
2022-07-02 14:32:02 +02:00
Hono - _**[炎] means flame🔥 in Japanese**_ - is a small, simple, and ultrafast web framework for Cloudflare Workers, Deno, and others.
2021-12-17 07:53:31 +01:00
2022-05-13 05:30:06 +02:00
```ts
import { Hono } from 'hono'
const app = new Hono()
2021-12-17 07:53:31 +01:00
app.get('/', (c) => c.text('Hono!!'))
2021-12-17 07:53:31 +01:00
app.fire()
```
2022-01-08 01:48:22 +01:00
## Features
2021-12-17 07:53:31 +01:00
2022-02-23 03:20:29 +01:00
- **Ultrafast** - the router does not use linear loops.
2022-05-13 05:30:06 +02:00
- **Zero-dependencies** - using only Service Worker and Web Standard API.
2022-03-06 02:27:26 +01:00
- **Middleware** - built-in middleware and ability to extend with your own middleware.
- **TypeScript** - first-class TypeScript support.
2022-07-02 14:32:02 +02:00
- **Multi-platform** - works on Cloudflare Workers, Fastly Compute@Edge, or Deno.
2021-12-14 21:17:56 +01:00
2022-07-02 11:29:09 +02:00
## Benchmarks
### Cloudflare Workers
- Machine: Apple MacBook Pro, 32 GiB, M1 Pro
- Scripts: [benchmarks/handle-event](https://github.com/honojs/hono/tree/master/benchmarks/handle-event)
2021-12-27 17:34:09 +01:00
2022-03-06 02:27:26 +01:00
**Hono is fastest**, compared to other routers for Cloudflare Workers.
```plain
hono - trie-router(default) x 389,510 ops/sec ±3.16% (85 runs sampled)
hono - regexp-router x 452,290 ops/sec ±2.64% (84 runs sampled)
itty-router x 206,013 ops/sec ±3.39% (90 runs sampled)
sunder x 323,131 ops/sec ±0.75% (97 runs sampled)
worktop x 191,218 ops/sec ±2.70% (91 runs sampled)
Fastest is hono - regexp-router
✨ Done in 43.56s.
2021-12-27 17:34:09 +01:00
```
2022-07-02 11:29:09 +02:00
### Deno
- Machine: Apple MacBook Pro, 32 GiB, M1 Pro, Deno v1.22.0
- Scripts: [benchmarks/deno](https://github.com/honojs/hono/tree/master/benchmarks/deno)
- Method: `autocannon -c 100 -d 40 -p 10 'http://127.0.0.1:8000/user/lookup/username/foo'`
**Hono is fastest**, compared to other frameworks for Deno.
| Framework | Version | Results |
| ----------------------------- | :-----: | ----------------------------------------: |
| **Hono - RegExpRouter** | 1.6.0 | **5118k requests in 40.02s, 865 MB read** |
| **Hono - TriRouter(default)** | 1.6.0 | **4932k requests in 40.02s, 833 MB read** |
| Faster | 5.7 | 3579k requests in 40.02s, 551 MB read |
| oak | 10.5.1 | 2385k requests in 40.02s, 403 MB read |
| opine | 2.2.0 | 1491k requests in 40.02s, 346 MB read |
2022-05-13 05:30:06 +02:00
## Why so fast?
Routers used in Hono are really smart.
- **TrieRouter**(default) - Implemented with Trie tree structure.
2022-05-16 15:15:34 +02:00
- **RegExpRouter** - Match the route with using one big Regex made before dispatch.
2022-05-13 05:30:06 +02:00
## Hono in 1 minute
2022-03-06 02:27:26 +01:00
A demonstration to create an application for Cloudflare Workers with Hono.
![Demo](https://user-images.githubusercontent.com/10682/151973526-342644f9-71c5-4fee-81f4-64a7558bb192.gif)
2022-04-26 00:58:08 +02:00
## Not only fast
Hono is fast. But not only fast.
### Write Less, do more
Built-in middleware make _"**Write Less, do more**"_ in reality. You can use a lot of middleware without writing code from scratch. Below are examples.
- [Basic Authentication](https://github.com/honojs/hono/tree/master/src/middleware/basic-auth/)
- [Cookie parsing / serializing](https://github.com/honojs/hono/tree/master/src/middleware/cookie/)
- [CORS](https://github.com/honojs/hono/tree/master/src/middleware/cors/)
- [ETag](https://github.com/honojs/hono/tree/master/src/middleware/etag/)
- [GraphQL Server](https://github.com/honojs/hono/tree/master/src/middleware/graphql-server/)
- [html](https://github.com/honojs/hono/tree/master/src/middleware/html/)
2022-06-10 11:37:30 +02:00
- [JSX](https://github.com/honojs/hono/tree/master/src/middleware/jsx/)
2022-04-27 01:59:42 +02:00
- [JWT Authentication](https://github.com/honojs/hono/tree/master/src/middleware/jwt/)
- [Logger](https://github.com/honojs/hono/tree/master/src/middleware/logger/)
- [Mustache template engine](https://github.com/honojs/hono/tree/master/src/middleware/mustache/) (Only for Cloudflare Workers)
- [JSON pretty printing](https://github.com/honojs/hono/tree/master/src/middleware/pretty-json/)
- [Serving static files](https://github.com/honojs/hono/tree/master/src/middleware/serve-static/) (Only for Cloudflare Workers)
2022-04-26 00:58:08 +02:00
2022-05-13 05:30:06 +02:00
To enable logger and Etag middleware with just this code.
2022-04-26 00:58:08 +02:00
2022-05-13 05:30:06 +02:00
```ts
2022-04-26 00:58:08 +02:00
import { Hono } from 'hono'
2022-05-13 05:30:06 +02:00
import { etag } from 'hono/etag'
2022-04-26 00:58:08 +02:00
import { logger } from 'hono/logger'
const app = new Hono()
2022-05-14 11:23:51 +02:00
app.use('*', etag(), logger())
2022-05-13 05:30:06 +02:00
```
And, the routing of Hono is so flexible. It's easy to construct large web applications.
```ts
2022-05-16 15:15:34 +02:00
import { Hono } from 'hono'
import { basicAuth } from 'hono/basic-auth'
2022-05-13 05:30:06 +02:00
2022-05-16 15:15:34 +02:00
const v1 = new Hono()
2022-05-13 05:30:06 +02:00
v1.get('/posts', (c) => {
2022-05-31 00:51:23 +02:00
return c.text('list posts')
2022-05-13 05:30:06 +02:00
})
2022-05-16 15:15:34 +02:00
.post(basicAuth({ username, password }), (c) => {
2022-05-13 05:30:06 +02:00
return c.text('created!', 201)
})
.get('/posts/:id', (c) => {
const id = c.req.param('id')
return c.text(`your id is ${id}`)
})
2022-05-16 15:15:34 +02:00
const app = new Hono()
2022-05-13 05:30:06 +02:00
app.route('/v1', v1)
2022-04-26 00:58:08 +02:00
```
2022-05-13 05:30:06 +02:00
### Web Standard
Request and Response object used in Hono are extensions of the Web Standard [Fetch API](https://developer.mozilla.org/ja/docs/Web/API/Fetch_API). If you are familiar with that, you don't need to know more than that.
2022-04-26 00:58:08 +02:00
### Developer Experience
2022-05-13 05:30:06 +02:00
Hono provides fine _"**Developer Experience**"_. Easy access to Request/Response thanks to the `Context` object.
2022-04-26 00:58:08 +02:00
Above all, Hono is written in TypeScript. So, Hono has _"**Types**"_!
For example, the named path parameters will be literal types.
2022-02-15 09:19:53 +01:00
![Demo](https://user-images.githubusercontent.com/10682/154179671-9e491597-6778-44ac-a8e6-4483d7ad5393.png)
2022-02-15 09:19:53 +01:00
2021-12-14 21:17:56 +01:00
## Install
2022-02-23 03:20:29 +01:00
You can install Hono from the npm registry.
2022-04-20 11:25:01 +02:00
```sh
npm install hono
2021-12-14 21:17:56 +01:00
```
2021-12-20 03:58:40 +01:00
## Methods
2022-02-23 03:20:29 +01:00
An instance of `Hono` has these methods.
2022-05-22 12:14:12 +02:00
- app.**HTTP_METHOD**(\[path,\]handler|middleware...)
- app.**all**(\[path,\]handler|middleware...)
- app.**route**(path, \[app\])
- app.**use**(\[path,\]middleware)
- app.**notFound**(handler)
- app.**onError**(err, handler)
2022-01-05 21:19:16 +01:00
- app.**fire**()
- app.**fetch**(request, env, event)
2022-05-22 12:14:12 +02:00
- app.**request**(path, options)
2021-12-20 03:58:40 +01:00
2021-12-17 07:53:31 +01:00
## Routing
### Basic
2021-12-14 21:17:56 +01:00
2022-05-13 05:30:06 +02:00
```ts
2021-12-20 23:34:38 +01:00
// HTTP Methods
app.get('/', (c) => c.text('GET /'))
app.post('/', (c) => c.text('POST /'))
2022-05-16 15:15:34 +02:00
app.put('/', (c) => c.text('PUT /'))
app.delete('/', (c) => c.text('DELETE /'))
2021-12-20 23:34:38 +01:00
// Wildcard
app.get('/wild/*/card', (c) => {
return c.text('GET /wild/*/card')
2021-12-20 23:34:38 +01:00
})
2021-12-20 03:58:40 +01:00
2021-12-20 23:34:38 +01:00
// Any HTTP methods
app.all('/hello', (c) => c.text('Any Method /hello'))
2021-12-20 03:58:40 +01:00
```
2021-12-17 07:53:31 +01:00
### Named Parameter
2021-12-14 21:17:56 +01:00
2022-05-13 05:30:06 +02:00
```ts
2021-12-21 09:37:02 +01:00
app.get('/user/:name', (c) => {
const name = c.req.param('name')
2021-12-17 07:53:31 +01:00
...
})
```
2022-05-16 15:15:34 +02:00
or all parameters at once:
```ts
app.get('/posts/:id/comment/:comment_id', (c) => {
const { id, comment_id } = c.req.param()
...
})
```
2021-12-17 07:53:31 +01:00
### Regexp
2022-05-13 05:30:06 +02:00
```ts
2021-12-21 09:37:02 +01:00
app.get('/post/:date{[0-9]+}/:title{[a-z]+}', (c) => {
2022-05-16 15:15:34 +02:00
const { date, title } = c.req.param()
2021-12-17 07:53:31 +01:00
...
2022-02-23 03:20:29 +01:00
})
2021-12-14 21:17:56 +01:00
```
### Chained route
2022-05-13 05:30:06 +02:00
```ts
app
.get('/endpoint', (c) => {
return c.text('GET /endpoint')
})
.post((c) => {
return c.text('POST /endpoint')
})
.delete((c) => {
return c.text('DELETE /endpoint')
})
```
### no strict
If `strict` is set false, `/hello`and`/hello/` are treated the same.
2022-05-13 05:30:06 +02:00
```ts
const app = new Hono({ strict: false }) // Default is true
app.get('/hello', (c) => c.text('/hello or /hello/'))
```
### async/await
2022-01-03 10:11:46 +01:00
```js
app.get('/fetch-url', async (c) => {
2022-01-03 10:11:46 +01:00
const response = await fetch('https://example.com/')
return c.text(`Status is ${response.status}`)
2022-01-03 10:11:46 +01:00
})
```
2022-05-16 15:15:34 +02:00
## Grouping
2022-05-13 05:30:06 +02:00
2022-05-16 15:15:34 +02:00
Group the routes with `Hono` instance and add them to the main app with `route` method.
2022-05-13 05:30:06 +02:00
```ts
2022-05-16 15:15:34 +02:00
const book = new Hono()
2022-05-13 05:30:06 +02:00
book.get('/', (c) => c.text('List Books')) // GET /book
book.get('/:id', (c) => {
// GET /book/:id
const id = c.req.param('id')
return c.text('Get Book: ' + id)
})
book.post('/', (c) => c.text('Create Book')) // POST /book
2022-05-16 15:15:34 +02:00
const app = new Hono()
2022-05-13 05:30:06 +02:00
app.route('/book', book)
```
2021-12-20 03:58:40 +01:00
## Middleware
2022-05-26 03:06:10 +02:00
Middleware works after/before Handler. We can get `Request` before dispatching or manipulate `Response` after dispatching.
2022-05-13 05:30:06 +02:00
### Definition of Middleware
2022-05-26 03:06:10 +02:00
- Handler - should return `Response` object. Only one handler will be called.
- Middleware - should return nothing, will be proceeded to next middleware with `await next()`
The user can register middleware using `c.use` or using `c.HTTP_METHOD` as well as the handlers. For this feature, it's easy to specify the path and the method.
```ts
// match any method, all routes
app.use('*', logger())
// specify path
app.use('/posts/*', cors())
// specify method and path
app.post('/posts/*', basicAuth(), bodyParse())
```
If the handler returns `Response`, it will be used for the end-user, and stopping the processing.
```ts
app.post('/posts', (c) => c.text('Created!', 201))
```
In this case, four middleware are processed before dispatching like this:
```ts
logger() -> cors() -> basicAuth() -> bodyParse() -> *handler*
```
2022-05-13 05:30:06 +02:00
2022-03-06 02:27:26 +01:00
### Built-in Middleware
2022-01-01 08:22:35 +01:00
Hono has built-in middleware.
2022-05-13 05:30:06 +02:00
```ts
import { Hono } from 'hono'
import { poweredBy } from 'hono/powered-by'
import { logger } from 'hono/logger'
import { basicAuth } from 'hono/basicAuth'
2022-01-01 08:22:35 +01:00
const app = new Hono()
2022-01-01 08:22:35 +01:00
app.use('*', poweredBy())
app.use('*', logger())
2022-02-23 03:20:29 +01:00
app.use(
'/auth/*',
basicAuth({
username: 'hono',
password: 'acoolproject',
})
)
2022-01-01 08:22:35 +01:00
```
Available built-in middleware is listed on [src/middleware](https://github.com/honojs/hono/tree/master/src/middleware).
2022-01-01 08:22:35 +01:00
### Custom Middleware
2022-02-23 03:20:29 +01:00
You can write your own middleware.
2022-05-13 05:30:06 +02:00
```ts
// Custom logger
app.use('*', async (c, next) => {
2021-12-21 09:37:02 +01:00
console.log(`[${c.req.method}] ${c.req.url}`)
2022-01-03 10:11:46 +01:00
await next()
})
2021-12-20 03:58:40 +01:00
2022-01-08 01:48:22 +01:00
// Add a custom header
app.use('/message/*', async (c, next) => {
2022-01-03 10:11:46 +01:00
await next()
2022-02-28 17:50:23 +01:00
c.header('x-message', 'This is middleware!')
})
2021-12-20 18:35:03 +01:00
app.get('/message/hello', (c) => c.text('Hello Middleware!'))
2021-12-20 03:58:40 +01:00
```
2022-02-26 08:19:53 +01:00
## Not Found
`app.notFound` for customizing Not Found Response.
```js
app.notFound((c) => {
return c.text('Custom 404 Message', 404)
})
```
2022-02-26 08:19:53 +01:00
## Error Handling
`app.onError` handle the error and return the customized Response.
```js
app.onError((err, c) => {
console.error(`${err}`)
return c.text('Custom Error Message', 500)
})
```
2021-12-21 09:37:02 +01:00
## Context
2022-05-13 05:30:06 +02:00
To handle Request and Response, you can use `Context` object.
### c.req
2021-12-21 09:37:02 +01:00
2022-05-13 05:30:06 +02:00
```ts
// Get Request object
2021-12-21 09:37:02 +01:00
app.get('/hello', (c) => {
2022-01-01 16:32:01 +01:00
const userAgent = c.req.headers.get('User-Agent')
2021-12-21 09:37:02 +01:00
...
})
// Shortcut to get a header value
app.get('/shortcut', (c) => {
const userAgent = c.req.header('User-Agent')
...
})
// Query params
app.get('/search', (c) => {
const query = c.req.query('q')
...
})
2022-05-16 15:15:34 +02:00
// Get all params at once
app.get('/search', (c) => {
const { q, limit, offset } = c.req.query()
...
})
// Multiple query values
app.get('/search', (c) => {
const queries = c.req.queries('q')
// ---> GET search?q=foo&q=bar
// queries[0] => foo, queries[1] => bar
...
})
// Captured params
app.get('/entry/:id', (c) => {
const id = c.req.param('id')
...
})
2021-12-21 09:37:02 +01:00
```
### Shortcuts for Response
2022-05-13 05:30:06 +02:00
```ts
app.get('/welcome', (c) => {
// Set headers
c.header('X-Message', 'Hello!')
c.header('Content-Type', 'text/plain')
2022-05-13 05:30:06 +02:00
// Set HTTP status code
c.status(201)
2022-05-13 05:30:06 +02:00
// Return the response body
return c.body('Thank you for comming')
2022-02-23 03:20:29 +01:00
})
```
2022-02-23 03:20:29 +01:00
The Response is the same as below.
2022-05-13 05:30:06 +02:00
```ts
2022-02-23 03:20:29 +01:00
new Response('Thank you for comming', {
status: 201,
headers: {
'X-Message': 'Hello',
'Content-Type': 'text/plain',
},
})
```
### c.text()
2022-03-06 02:27:26 +01:00
Render text as `Content-Type:text/plain`.
2021-12-20 03:58:40 +01:00
2022-05-13 05:30:06 +02:00
```ts
app.get('/say', (c) => {
return c.text('Hello!')
2021-12-20 03:58:40 +01:00
})
```
### c.json()
2022-02-23 03:20:29 +01:00
Render JSON as `Content-Type:application/json`.
2022-05-13 05:30:06 +02:00
```ts
app.get('/api', (c) => {
return c.json({ message: 'Hello!' })
})
```
2022-01-08 05:51:47 +01:00
### c.html()
2022-02-23 03:20:29 +01:00
Render HTML as `Content-Type:text/html`.
2022-01-08 05:51:47 +01:00
2022-05-13 05:30:06 +02:00
```ts
app.get('/', (c) => {
2022-01-08 05:51:47 +01:00
return c.html('<h1>Hello! Hono!</h1>')
})
```
### c.notFound()
Return the `Not Found` Response.
2022-05-13 05:30:06 +02:00
```ts
app.get('/notfound', (c) => {
return c.notFound()
})
```
### c.redirect()
2022-02-23 03:20:29 +01:00
Redirect, default status code is `302`.
2022-05-13 05:30:06 +02:00
```ts
app.get('/redirect', (c) => c.redirect('/'))
app.get('/redirect-permanently', (c) => c.redirect('/', 301))
```
### c.res
2022-05-13 05:30:06 +02:00
```ts
// Response object
2022-05-16 15:15:34 +02:00
app.use('/', async (c, next) => {
await next()
c.res.headers.append('X-Debug', 'Debug message')
})
```
### c.executionCtx
```ts
// ExecutionContext object
app.get('/foo', async (c) => {
c.executionCtx.waitUntil(
c.env.KV.put(key, data)
)
...
})
```
### c.event
2022-05-13 05:30:06 +02:00
```ts
// FetchEvent object (only set when using Service Worker syntax)
2022-05-16 15:15:34 +02:00
app.get('/foo', async (c) => {
c.event.waitUntil(
2022-05-16 15:15:34 +02:00
c.env.KV.put(key, data)
)
2022-05-16 15:15:34 +02:00
...
})
```
### c.env
Environment variables, secrets, and KV namespaces are known as bindings. Regardless of type, bindings are always available as global variables and can be accessed via the context `c.env.BINDING_KEY`.
2022-05-13 05:30:06 +02:00
```ts
// Environment object for Cloudflare Workers
app.get('*', async c => {
const counter = c.env.COUNTER
...
})
```
2022-01-05 21:19:16 +01:00
## fire
2022-02-23 03:20:29 +01:00
`app.fire()` do this.
2022-01-05 21:19:16 +01:00
2022-05-13 05:30:06 +02:00
```ts
2022-01-05 21:19:16 +01:00
addEventListener('fetch', (event) => {
event.respondWith(this.handleEvent(event))
})
```
## fetch
`app.fetch` for Cloudflare Module Worker syntax.
2022-05-13 05:30:06 +02:00
```ts
export default {
fetch(request: Request, env: Env, ctx: ExecutionContext) {
return app.fetch(request, env, ctx)
},
}
2022-05-13 05:30:06 +02:00
```
2022-02-23 03:20:29 +01:00
or just do:
2022-05-13 05:30:06 +02:00
```ts
export default app
```
## request
`request` is a useful method for testing.
```js
test('GET /hello is ok', async () => {
const res = await app.request('http://localhost/hello')
expect(res.status).toBe(200)
})
```
## router
2022-05-19 08:37:33 +02:00
The `router` option specify which router is used inside. The default router is `TrieRouter`. If you want to use `RexExpRouter`, write like this:
2022-05-19 08:37:33 +02:00
```ts
import { RegExpRouter } from 'hono/router/reg-exp-router'
const app = new Hono({ router: new RegExpRouter() })
2022-05-19 08:37:33 +02:00
```
2022-06-17 11:48:50 +02:00
## Routing priority
2022-05-26 03:06:10 +02:00
2022-06-17 11:48:50 +02:00
Handlers or middleware will be executed in registration order.
2022-05-26 03:06:10 +02:00
```ts
app.get('/book/a', (c) => c.text('a')) // a
app.get('/book/:slug', (c) => c.text('common')) // common
```
```http
2022-06-17 11:48:50 +02:00
GET /book/a ---> `a`
GET /book/b ---> `common`
2022-05-26 03:06:10 +02:00
```
2022-06-17 11:48:50 +02:00
When a handler is executed, the process will be stopped.
2022-05-26 03:06:10 +02:00
```ts
2022-06-17 11:48:50 +02:00
app.get('*', (c) => c.text('common')) // common
app.get('/foo', (c) => c.text('foo')) // foo
2022-05-26 03:06:10 +02:00
```
2022-06-17 11:48:50 +02:00
```http
GET /foo ---> `common` // foo will not be dispatched
```
If you have the middleware that you want to execute, write the code above the handler.
```ts
app.use('*', logger())
app.get('/foo', (c) => c.text('foo'))
```
If you want a "_fallback_" handler, write the code below the other handler.
```ts
app.get('/foo', (c) => c.text('foo')) // foo
app.get('*', (c) => c.text('fallback')) // fallback
```
```http
GET /bar ---> `fallback`
2022-05-26 03:06:10 +02:00
```
## Cloudflare Workers with Hono
2022-01-02 14:46:36 +01:00
2022-05-13 05:30:06 +02:00
Using [Wrangler](https://developers.cloudflare.com/workers/cli-wrangler/), you can develop the application locally and publish it with few commands.
2022-01-07 09:34:12 +01:00
Let's write your first code for Cloudflare Workers with Hono.
2022-01-02 14:46:36 +01:00
2022-05-13 05:30:06 +02:00
### 1. `wrangler init`
2022-01-02 14:46:36 +01:00
2022-03-05 02:38:33 +01:00
Initialize as a wrangler project.
2022-01-02 14:46:36 +01:00
2022-03-05 02:38:33 +01:00
```
2022-05-13 05:30:06 +02:00
mkdir hono-example
cd hono-example
npx wrangler init -y
2022-01-02 14:46:36 +01:00
```
2022-05-13 05:30:06 +02:00
### 2. `npm install hono`
2022-01-02 14:46:36 +01:00
2022-02-23 03:20:29 +01:00
Install `hono` from the npm registry.
2022-01-02 14:46:36 +01:00
2022-05-13 05:30:06 +02:00
```
npm init -y
2022-04-20 11:25:01 +02:00
npm i hono
2022-01-02 14:46:36 +01:00
```
2022-05-13 05:30:06 +02:00
### 3. Write your app
2022-01-02 14:46:36 +01:00
2022-05-13 05:30:06 +02:00
Edit `src/index.ts`. Only 4 lines!!
2022-01-02 14:46:36 +01:00
2022-05-13 05:30:06 +02:00
```ts
// src/index.ts
import { Hono } from 'hono'
2022-01-02 14:46:36 +01:00
const app = new Hono()
app.get('/', (c) => c.text('Hello! Hono!'))
2022-01-02 14:46:36 +01:00
app.fire()
```
2022-05-13 05:30:06 +02:00
### 4. Run
2022-01-02 14:46:36 +01:00
2022-02-23 03:20:29 +01:00
Run the development server locally. Then, access `http://127.0.0.1:8787/` in your Web browser.
2022-01-02 14:46:36 +01:00
2022-05-13 05:30:06 +02:00
```
npx wrangler dev
2022-01-02 14:46:36 +01:00
```
2022-05-13 05:30:06 +02:00
### 5. Publish
Deploy to Cloudflare. That's all!
2022-05-13 05:30:06 +02:00
```
2022-05-14 00:51:20 +02:00
npx wrangler publish ./src/index.ts
2022-02-23 03:20:29 +01:00
```
## Starter template
You can start making your Cloudflare Workers application with [the starter template](https://github.com/honojs/hono-minimal). It is really minimal using TypeScript, esbuild, Miniflare, and Jest.
2022-02-23 03:20:29 +01:00
2022-05-31 00:51:23 +02:00
To generate a project skeleton, run this command.
2022-02-23 03:20:29 +01:00
2022-05-13 05:30:06 +02:00
```
npx create-cloudflare my-app https://github.com/honojs/hono-minimal
```
2022-05-16 15:15:34 +02:00
## Practical Example
How about writing web API with Hono?
```ts
import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { basicAuth } from 'hono/basic-auth'
import { prettyJSON } from 'hono/pretty-json'
2022-05-19 08:37:33 +02:00
import { getPosts, getPost, createPost, Post } from './model'
2022-05-16 15:15:34 +02:00
const app = new Hono()
app.get('/', (c) => c.text('Pretty Blog API'))
app.use('*', prettyJSON())
app.notFound((c) => c.json({ message: 'Not Found', ok: false }, 404))
export interface Bindings {
USERNAME: string
PASSWORD: string
}
const api = new Hono<Bindings>()
2022-05-26 03:06:10 +02:00
api.use('/posts/*', cors())
2022-05-16 15:15:34 +02:00
api.get('/posts', (c) => {
const { limit, offset } = c.req.query()
const posts = getPosts({ limit, offset })
return c.json({ posts })
})
api.get('/posts/:id', (c) => {
const id = c.req.param('id')
const post = getPost({ id })
return c.json({ post })
})
api.post(
'/posts',
async (c, next) => {
const auth = basicAuth({ username: c.env.USERNAME, password: c.env.PASSWORD })
await auth(c, next)
},
async (c) => {
2022-05-19 08:37:33 +02:00
const post = await c.req.json<Post>()
2022-05-16 15:15:34 +02:00
const ok = createPost({ post })
return c.json({ ok })
}
)
app.route('/api', api)
export default app
```
## Other Examples
2022-04-27 08:18:55 +02:00
- Hono Examples - <https://github.com/honojs/examples>
2022-07-02 11:29:09 +02:00
## Deno
Hono also works with Deno. This feature is still experimental.
```tsx
/** @jsx jsx */
import { serve } from 'https://deno.land/std/http/server.ts'
import { Hono, logger, poweredBy, serveStatic, jsx } from 'https://deno.land/x/hono/mod.ts'
2022-07-02 11:29:09 +02:00
const app = new Hono()
app.use('*', logger(), poweredBy())
app.get('/favicon.ico', serveStatic({ path: './public/favicon.ico' }))
2022-07-02 11:29:09 +02:00
app.get('/', (c) => {
return c.html(<h1>Hello Deno!</h1>)
})
serve(app.fetch)
2022-07-02 11:29:09 +02:00
```
2021-12-14 21:31:37 +01:00
## Related projects
2022-02-23 03:20:29 +01:00
Implementation of the original router `TrieRouter` is inspired by [goblin](https://github.com/bmf-san/goblin). `RegExpRouter` is inspired by [Router::Boom](https://github.com/tokuhirom/Router-Boom). API design is inspired by [express](https://github.com/expressjs/express) and [koa](https://github.com/koajs/koa). [itty-router](https://github.com/kwhitley/itty-router), [Sunder](https://github.com/SunderJS/sunder), and [worktop](https://github.com/lukeed/worktop) are the other routers or frameworks for Cloudflare Workers.
2022-04-27 08:18:55 +02:00
- express - <https://github.com/expressjs/express>
- koa - <https://github.com/koajs/koa>
- itty-router - <https://github.com/kwhitley/itty-router>
- Sunder - <https://github.com/SunderJS/sunder>
- goblin - <https://github.com/bmf-san/goblin>
- worktop - <https://github.com/lukeed/worktop>
- Router::Boom - <https://github.com/tokuhirom/Router-Boom>
2021-12-14 21:31:37 +01:00
## Contributing
2022-04-26 00:58:08 +02:00
Contributions Welcome! You can contribute in the following ways.
- Write or fix documents
- Write code of middleware
- Fix bugs
- Refactor the code
2022-01-08 01:48:22 +01:00
- etc.
2022-02-15 09:19:53 +01:00
## Contributors
2022-05-13 05:30:06 +02:00
Thanks to [all contributors](https://github.com/honojs/hono/graphs/contributors)! Especially, [@metrue](https://github.com/metrue) and [@usualoma](https://github.com/usualoma)!
2022-02-15 09:19:53 +01:00
2021-12-14 20:26:22 +01:00
## Author
Yusuke Wada <https://github.com/yusukebe>
## License
2022-01-07 09:34:12 +01:00
Distributed under the MIT License. See [LICENSE](LICENSE) for more information.