Skip to main content

Getting Started

Model-written

contextmethodsetupanalysis

Getting Started

Hono makes setup, development, and deployment easy across runtimes

Using Hono is super easy. We can set up the project, write code, develop with a local server, and deploy quickly. The same code will work on any runtime, just with different entry points. Let's look at the basic usage of Hono.We can set up the project, write code, develop with a local server, and deploy quickly. The same code will work on any runtime, just with different entry points.Hono enables easy setup, coding, and deployment across runtimes The same code works on any runtime with different entry points, simplifying developmentHono enables easy setup, coding, and deployment across runtimesHono

Starter

Use create-hono to scaffold a starter template for your platform

Starter templates are available for each platform. Use the following "create-hono" command.Starter templates are available for each platform. Use the following "create-hono" command.Use create-hono command to start a starter template Starter templates are available for each platform, simplifying project initiationUse create-hono command to start a starter templatecreate-hono

npm create hono@latest my-app
yarn create hono my-app
pnpm create hono@latest my-app
bun create hono@latest my-app
deno init --npm hono@latest my-app

Then you will be asked which template you would like to use. Let's select Cloudflare Workers for this example.Then you will be asked which template you would like to use. Let's select Cloudflare Workers for this example.Select Cloudflare Workers template for this example The prompt asks which template to use, and this choice determines the project setupSelect Cloudflare Workers template for this exampleCloudflare Workers

? Which template do you want to use?
    aws-lambda
    bun
    cloudflare-pages
❯   cloudflare-workers
    deno
    fastly
    nextjs
    nodejs
    vercel

The template will be pulled into my-app, so go to it and install the dependencies.The template will be pulled into my-app, so go to it and install the dependencies.Navigate to my-app and install dependencies After the template is pulled, you must install dependencies to run the appNavigate to my-app and install dependenciesdependencies

cd my-app
npm i
cd my-app
yarn
cd my-app
pnpm i
cd my-app
bun i

Once the package installation is complete, run the following command to start up a local server.Once the package installation is complete, run the following command to start up a local server.Run npm run dev to start the local server After installing dependencies, this command launches the development serverRun npm run dev to start the local servernpm run dev

npm run dev
yarn dev
pnpm dev
bun run dev

Hello World

Write a basic Hono app in TypeScript with a single route

You can write code in TypeScript with the Cloudflare Workers development tool "Wrangler", Deno, Bun, or others without being aware of transpiling.You can write code in TypeScript with the Cloudflare Workers development tool "Wrangler", Deno, Bun, or others without being aware of transpiling.Write TypeScript code without worrying about transpiling Tools like Wrangler, Deno, and Bun handle transpilation automaticallyWrite TypeScript code without worrying about transpilingTypeScript

Write your first application with Hono in src/index.ts. The example below is a starter Hono application.Write your first application with Hono in src/index.ts. The example below is a starter Hono application.Write your first Hono app in src/index.ts The example starter application demonstrates basic Hono usageWrite your first Hono app in src/index.tssrc/index.ts

The import and the final export default parts may vary from runtime to runtime, but all of the application code will run the same code everywhere.The import and the final export default parts may vary from runtime to runtime, but all of the application code will run the same code everywhere.Import and export parts vary, but application code runs everywhere Runtime-specific entry points differ, yet the core logic remains portableImport and export parts vary, but application code runs everywhereapplication code

import { Hono } from 'hono'

const app = new Hono()

app.get('/', (c) => {
  return c.text('Hello Hono!')
})

export default app

Start the development server and access http://localhost:8787 with your browser.Start the development server and access http://localhost:8787 with your browser.Start dev server and access http://localhost:8787 This URL is the default address for the development serverStart dev server and access http://localhost:8787localhost:8787

npm run dev
yarn dev
pnpm dev
bun run dev

Return JSON

Return JSON easily with c.json for a GET route

Returning JSON is also easy. The following is an example of handling a GET Request to /api/hello and returning an application/json Response.Returning JSON is also easy. The following is an example of handling a GET Request to /api/hello and returning an application/json Response.Return JSON easily with c.json for a GET route The example shows handling a GET to /api/hello and returning application/jsonReturn JSON easily with c.json for a GET routec.json

app.get('/api/hello', (c) => {
  return c.json({
    ok: true,
    message: 'Hello Hono!',
  })
})

Request and Response

Access path params, queries, headers, and handle various HTTP methods

Getting a path parameter, URL query value, and appending a Response header is written as follows.Getting a path parameter, URL query value, and appending a Response header is written as follows.Access path params, query values, and set headers easily The code example demonstrates retrieving id and page, and setting X-Message headerAccess path params, query values, and set headers easilypath params

app.get('/posts/:id', (c) => {
  const page = c.req.query('page')
  const id = c.req.param('id')
  c.header('X-Message', 'Hi!')
  return c.text(`You want to see ${page} of ${id}`)
})

We can easily handle POST, PUT, and DELETE not only GET.We can easily handle POST, PUT, and DELETE not only GET.Handle POST, PUT, and DELETE methods easily, not just GET Hono supports all HTTP methods with simple route definitionsHandle POST, PUT, and DELETE methods easily, not just GETPOST

app.post('/posts', (c) => c.text('Created!', 201))
app.delete('/posts/:id', (c) =>
  c.text(`${c.req.param('id')} is deleted!`)
)

Return HTML

Return HTML using the html helper or JSX syntax

You can write HTML with the html Helper or using JSX syntax. If you want to use JSX, rename the file to src/index.tsx and configure it (check with each runtime as it is different). Below is an example using JSX.You can write HTML with the html Helper or using JSX syntax. If you want to use JSX, rename the file to src/index.tsx and configure it (check with each runtime as it is different).Return HTML using html helper or JSX syntax JSX requires renaming the file to .tsx and configuring the runtimeReturn HTML using html helper or JSX syntaxHTML

const View = () => {
  return (
    <html>
      <body>
        <h1>Hello Hono!</h1>
      </body>
    </html>
  )
}

app.get('/page', (c) => {
  return c.html(<View />)
})

Return raw Response

Return a raw Response object directly from a route

You can also return the raw Response.You can also return the raw Response.You can return the raw Response object directly This allows full control over the response, bypassing Hono's helpersYou can return the raw Response object directlyResponse

app.get('/', () => {
  return new Response('Good morning!')
})

Using Middleware

Use middleware like basicAuth to add authentication easily

Middleware can do the hard work for you. For example, add in Basic Authentication.Middleware can do the hard work for you. For example, add in Basic Authentication.Use middleware like basicAuth to add authentication easily The example shows protecting /admin routes with basic authenticationUse middleware like basicAuth to add authentication easilybasicAuth

import { basicAuth } from 'hono/basic-auth'

// ...

app.use(
  '/admin/*',
  basicAuth({
    username: 'admin',
    password: 'secret',
  })
)

app.get('/admin', (c) => {
  return c.text('You are authorized!')
})

There are useful built-in middleware including Bearer and authentication using JWT, CORS and ETag. Hono also provides third-party middleware using external libraries such as GraphQL Server and Firebase Auth. And, you can make your own middleware.There are useful built-in middleware including Bearer and authentication using JWT, CORS and ETag. Hono also provides third-party middleware using external libraries such as GraphQL Server and Firebase Auth. And, you can make your own middleware.Hono offers built-in and third-party middleware, and custom middleware Built-in includes Bearer, JWT, CORS, ETag; third-party uses external librariesHono offers built-in and third-party middleware, and custom middlewaremiddleware

Adapter

Adapters provide platform-specific functions like WebSocket handling

There are Adapters for platform-dependent functions, e.g., handling static files or WebSocket. They are published as separate packages. For example, to handle WebSocket in Cloudflare Workers, install and import @hono/cloudflare-workers.There are Adapters for platform-dependent functions, e.g., handling static files or WebSocket. They are published as separate packages. For example, to handle WebSocket in Cloudflare Workers, install and import @hono/cloudflare-workers.Adapters provide platform-specific functions like WebSocket handling They are separate packages, e.g., @hono/cloudflare-workers for WebSocket in WorkersAdapters provide platform-specific functions like WebSocket handlingAdapters

import { upgradeWebSocket } from '@hono/cloudflare-workers'

app.get(
  '/ws',
  upgradeWebSocket((c) => {
    // ...
  })
)

Next step

Follow platform-specific guides for setup and deployment

Most code will work on any platform, but there are guides for each. For instance, how to set up projects or how to deploy. Please see the page for the exact platform you want to use to create your application!Most code will work on any platform, but there are guides for each. For instance, how to set up projects or how to deploy. Please see the page for the exact platform you want to use to create your application!Follow platform-specific guides for setup and deployment Most code is portable, but setup and deployment details differ per platformFollow platform-specific guides for setup and deploymentplatform-specific guides