Saturday, October 15, 2022
HomeWeb DevelopmentConstruct an online utility with Hono

Construct an online utility with Hono


Choosing the proper device for an online utility could be difficult given the abundance of obtainable choices. Pace is one consideration that’s typically high of thoughts when choosing a framework. Quick load time is a precedence for net purposes, as customers dislike extreme wait instances.

This text introduces Hono, a brand new, versatile net utility framework that could be very quick. Based on check outcomes printed on the framework’s web site, Hono is quicker than different routers for Cloudflare Staff, resembling Sunder, Itty Router, and Worktop, and likewise quicker than different frameworks for Deno and Bun.

Within the tutorial portion of this put up, we’ll display find out how to make a weblog app utilizing Cloudflare Staff and Hono.

Contents

Conditions

To get essentially the most out of this tutorial, guarantee you have got the next:

What’s Hono?

Hono is a light-weight, easy, and quick net framework for Cloudflare Staff, Deno, Bun, and different purposes. It’s a fashionable net utility that’s each quick and versatile. It gives inbuilt help for TypeScript, and simple growth in an area surroundings. Utilizing Hono, It’s simple to create publishable net purposes with Deno, Bun, and Cloudflare Staff.

Why use Hono?

Hono has many cool options, which is why it’s liked and utilized by many builders. Listed here are a few of Hono’s options:

  • Ultrafast router with out linear loops
  • Inbuilt help for TypeScript
  • Makes use of Service Staff and Internet Commonplace API with zero dependencies
  • Permits use of inbuilt middleware, customized middleware, and third-party middleware
  • Integrates with a number of platforms, resembling Cloudflare Staff, Fastfly, [email protected], Deno, and Bun

Demo: Constructing a weblog app with Hono

Let’s create an online utility whereas we discover Hono’s options. We’ll arrange the undertaking with Cloudflare Staff, create a to-do API, carry out CRUD operations, implement authentication, and add middleware.

Getting began

To get began, let’s create our first Hono utility with Cloudflare Staff.

First, create a brand new folder for the undertaking, like so:

mkdir hono-app && cd hono-app

Then, initialize a brand new undertaking with Wrangler, the Cloudflare Staff command-line device:

npx wrangler init -y

The above command will generate the next folder construction:

hono-example
 ┣ src
 ┃ ┗ index.ts
 ┣ .gitignore
 ┣ package-lock.json
 ┣ package deal.json
 ┣ tsconfig.json
 ┗ wrangler.toml

Putting in Hono

To arrange the appliance, begin by putting in the Hono package deal by operating the next command:

npm set up hono

Subsequent, create a Hono server, like so:

import { Hono } from 'hono'
const app = new Hono()

app.get("https://weblog.logrocket.com/", (c) => c.textual content('Whats up from Hono'))

app.fireplace()

Within the above code, we imported the Hono package deal and initialized a brand new Hono app occasion. With the app occasion, we’ve entry to all of Hono’s accessible options. We additionally exported the app occasion, in order that Cloudflare Staff can run the appliance in a service employee mode.

Subsequent, run the next command within the undertaking root listing to begin the appliance:

npx wrangler dev

This command will run the appliance on localhost:8787. You may check that out in your browser.

Creating routes

Hono makes routing as versatile and intuitive as attainable; it is rather much like the best way you’d deal with routing with a framework like Specific.js.

Let’s create an API path to carry out some CRUD operations. We’ll create a weblog API to learn and create blogs.

We’ll begin by creating a sort and a variable for the blogs. Add the next code to the index.ts file:

sort BLOG = {
  id: quantity,
  title: string,
  content material: string
}

const blogs: BLOG[] = []

Subsequent, we’ll outline the API routes with the beneath code:

app.get('/api/blogs', (c) => c.json(blogs))

app.get('/api/blogs/:id', (c) => {
  const { id } = c.req.param()
  const weblog = blogs.filter(information => information.id === parseInt(id))
  return c.json(weblog)
})

app.put up('/api/blogs', async (c) => {
  const physique = await c.req.parseBody() as BLOG;
  if (!physique) return c.json({ standing: 401, message: "The request payload is required" })
  const newBlog = {
    id: blogs.size + 1,
    title: physique.title,
    content material: physique.content material
  }
  blogs.push(newBlog)
  return c.json({ information: newBlog })
})

Like Specific.js, Hono offers a number of strategies (e.g., get, put up, replace, delete) for us to carry out operations. Every of those strategies has a callback that takes c as a parameter. The c parameter provides the consumer entry to the strategy we have to entry the request parameters and payloads, in addition to to reply to requests.

Including authentication

Hono offers middleware so as to add authentication to our utility in a snap. Hono gives three sorts of authentication middleware: fundamental authentication, bearer authentication, and JWT authentication. Particulars on every of all these authentication could be discovered right here.

For this demonstration, we’ll implement the fundamental authentication. To get began, import the basicAuth middleware from Hono and use the next code:

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

app.use(
  '/api/*',
  basicAuth({
    username: 'clinton',
    password: '1234',
  })
)

This middleware will stop unauthorized customers from requesting any endpoint that begins with /api. Additionally, it can show a sign-in UI that customers should log in to earlier than entry can be granted:

Sign-in UI

If the username and password the consumer enters match the username and password within the middleware, Hono will create a session and permit entry to the routes on subsequent requests.

Rendering static recordsdata

Hono offers serveStatic middleware to permit the rendering of static recordsdata situated within the listing specified within the middleware’s root choice.

To get began, create an property file within the undertaking’s root listing. Then, replace the wrangler.toml file to specify the property listing, like so:

[site]
bucket = "./property"

Subsequent, we’ll have to create or add our asset recordsdata to the property folder.

For this demonstration, we’ll render an HTML web page. So, create an index.html file within the property folder with the beneath markup:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Suitable" content material="IE=edge">
    <meta title="viewport" content material="width=device-width, initial-scale=1.0">
    <title>Doc</title>
    <hyperlink rel="stylesheet" href="https://weblog.logrocket.com/static/model.css">
</head>
<physique>
    <h4>Whats up from Hono </h4>
</physique>
</html>

Now, arrange the static middleware within the index.ts file, like so:

app.use('/static/*', serveStatic({ root: './' }))
app.get("https://weblog.logrocket.com/", serveStatic({ path: './index.html' }));

Within the above code, we created a Hono middleware that can serve static content material on the /static endpoint. We additionally used the serverStatic middleware to specify the basis location of our property listing.

Dealing with CORS

To permit our utility to work together with a frontend framework, we have to implement CORS. Hono offers us with a cors middleware.

Import and arrange the middleware within the index.ts file:

import { cors } from 'hono/cors'
app.use('/api/*', cors())

Within the above code, we implement CORS on all endpoints in our utility that start with /api. By doing so, there gained’t be any CORS blocking when a consumer makes requests to those endpoints.

Deploying the appliance

Now, let’s deploy the appliance to Cloudflare by operating the next command:

npx wrangler publish ./src/index.ts

The above command will immediate you to authorize the appliance to entry your Cloudflare account.

After authorizing the appliance, await the deployment to finish. As soon as the deployment is accomplished, you’ll see the employee URL of your utility, much like that proven beneath:

Worker URL

Copy the hyperlink and try it out.


Extra nice articles from LogRocket:


Conclusion

On this tutorial, we explored find out how to construct an online utility with Hono. We mentioned what Hono is all about and why builders ought to think about using this framework. For example this level, we confirmed find out how to construct a weblog utility utilizing Cloudflare Staff and Hono.

To be taught extra about Hono’s options, go to the official documentation.

Now that you just’ve been launched to Hono, how will you employ it in your subsequent undertaking?

: Full visibility into your net and cellular apps

LogRocket is a frontend utility monitoring resolution that permits you to replay issues as in the event that they occurred in your personal browser. As an alternative of guessing why errors occur, or asking customers for screenshots and log dumps, LogRocket allows you to replay the session to rapidly perceive what went fallacious. It really works completely with any app, no matter framework, and has plugins to log further context from Redux, Vuex, and @ngrx/retailer.

Along with logging Redux actions and state, LogRocket data console logs, JavaScript errors, stacktraces, community requests/responses with headers + our bodies, browser metadata, and customized logs. It additionally devices the DOM to document the HTML and CSS on the web page, recreating pixel-perfect movies of even essentially the most advanced single-page and cellular apps.

.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments