Zurück zum Blog

Folgen und abonnieren

Hono on Fastly Compute: A Familiar Express-Style Experience at the Edge

Discover how to build Fastly Compute apps using Hono, a lightweight, Express-inspired web framework with Typescript support and a thriving community ecosystem.

Katsuyuki Omuro
Katsuyuki OmuroStaff Software Engineer, Developer Experience Engineering, Fastly

If you've ever built a web app with Express, you already know how to think about building web apps on Fastly Compute. Hono is an open-source web framework that runs on various platforms including Compute and gives you the same routing and middleware style you're used to, with TypeScript support and a thriving ecosystem to match. It's what Fastly now recommends for new Compute apps that want an Express-like interface.

Back in 2022, Fastly released Expressly, a small routing library that gave JavaScript developers on Compute an API shaped like the one in Express. It was never our goal to compete with other frameworks. The intent was to provide an interface to Compute that felt familiar to people who already knew Express.

A lot has happened since then. Hono, whose first commit landed in December 2021, has grown into a popular framework with an active community, and it does everything Expressly aimed to do and more. In this post, we’ll explore how your existing Express or Expressly knowledge applies to Hono on Fastly Compute, and how to get a service up and running in just a few minutes.

Why Hono?

Hono isn't a Fastly project. It's open source (MIT licensed, just like Expressly), created by Yusuke Wada and developed in the open by a community of contributors on GitHub. It has the familiar Express-style interface for defining routes and chaining middleware, and isn't tied to any one platform. Fastly Compute is one of several runtimes it supports, so what you learn here carries over to other places. It also comes with an ecosystem of plugins and middleware built by its community, along with an active group of developers who are building, answering questions, and sharing ideas.

That ecosystem is the part I'm most excited about: instead of writing every piece of cross-cutting logic yourself, you can reach for community-built middleware and spend your time on what makes your application unique.

As for Expressly, remember that it was only ever meant to give you a familiar coding API and Hono fills that need perfectly.

From Express to Hono on Compute

You already know how Express structures a web app: you create an app, register some routes, and add middleware to handle the things that cut across them. Let's look at how that maps to Hono on Compute, starting with the classic hello world.

Express on Node.js

import express from "express";

const app = express();

app.get("/", (req, res) => {
  res.send("Hello world!");
});

app.listen(3000);

Hono on Fastly Compute

import { Hono } from "hono";
import { fire } from "@fastly/hono-fastly-compute";

const app = new Hono();

app.get("/", (c) => {
  return c.text("Hello world!");
});

fire(app);

Look how similar they are! Both create an app, define a route with a method and a path, and send back a response. There are really just two differences here. First, handlers in Hono receive a single context object, c, instead of separate req and res objects. Second, instead of calling app.listen(), you hand your app over to Compute with fire(app).

Of course, real apps do more than say hello. Here's a slightly bigger example with middleware, a path parameter, a query string, a JSON response, a custom 404, and error handling. First, in Express:

import express from "express";

const app = express();

// Middleware
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

// A path parameter and a query string
app.get("/hello/:name", (req, res) => {
  const excited = req.query.excited === "true";
  res.json({ greeting: `Hello, ${req.params.name}${excited ? "!" : "."}` });
});

// Custom 404
app.use((req, res) => {
  res.status(404).send("Not found");
});

// Error handling
app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).send("Something went wrong");
});

app.listen(3000);

And the same app in Hono on Compute:

import { Hono } from "hono";
import { fire } from "@fastly/hono-fastly-compute";

const app = new Hono();

// Middleware
app.use(async (c, next) => {
  console.log(`${c.req.method} ${c.req.url}`);
  await next();
});

// A path parameter and a query string
app.get("/hello/:name", (c) => {
  const excited = c.req.query("excited") === "true";
  return c.json({ greeting: `Hello, ${c.req.param("name")}${excited ? "!" : "."}` });
});

// Custom 404
app.notFound((c) => c.text("Not found", 404));

// Error handling
app.onError((err, c) => {
  console.error(err);
  return c.text("Something went wrong", 500);
});

fire(app);

Every piece has a close counterpart. req.params and req.query become c.req.param() and c.req.query(), and res.json() becomes c.json(). Middleware calls await next() instead of next(). The custom 404 and error handlers move from catch-all middleware to app.notFound() and app.onError(). And instead of calling methods on res, you return the response.

What's Similar and What's Different

In other words, the mental model carries over almost entirely. You still register routes by method and path, still pull values out of path parameters, and still chain middleware to share logic across routes. What's different is the layer underneath. Express is built around the IncomingMessage and ServerResponse objects from Node.js, while Hono is built on the standard web Request and Response objects, the very same ones Compute itself uses. I wrote about this difference in an earlier post, Node.js-style HTTP interfaces for Compute, if you'd like the background.

Below are some other comparisons between Expressly and Hono on Compute:

  • Starting the app: Express listens on a port. With Hono on Compute, you hand your app to the platform with fire(app).

  • Resources: In Compute, you work with Fastly resources such as backends, KV Stores, and Secret Stores. Hono gives them to your handlers as typed bindings on c.env. More on that below.

  • Calling an origin: With Hono on Compute, it's still fetch, with Compute's backend option and, if you want it, a CacheOverride.

  • Static files: There's no filesystem to serve files from, so there's no express.static(). Instead, the Static Publisher puts your files into a KV Store so your app can serve them, and we'll look at an example below. The starter kit also shows how to embed a single file at build time with includeBytes.

  • TypeScript: Hono is built with TypeScript in mind, so your editor can help with types for routes, bindings, and middleware.

Coming from Expressly?

If you've been using Expressly, moving to Hono mostly comes down to swapping a few names. Here's the hello world from the Expressly announcement:

import { Router } from "@fastly/expressly";

const router = new Router();

router.get("/", async (req, res) => {
  return res.send("Hello world!");
});

router.listen();

And here it is in Hono:

import { Hono } from "hono";
import { fire } from "@fastly/hono-fastly-compute";

const app = new Hono();

app.get("/", (c) => {
  return c.text("Hello world!");
});

fire(app);

Router becomes Hono, router.listen() becomes fire(app), and handlers take a context object instead of req and res. Many of the other things you used in Expressly have an equivalent too:

  • Path and search parameters: c.req.param() and c.req.query().

  • Cookies: Hono's cookie helpers, getCookie() and setCookie(), from hono/cookie.

  • Middleware and error handling: app.use() and app.onError().

  • Custom 404 responses: app.notFound().

  • Vary and Surrogate-Key headers: set them directly with c.header().

Expressly could also send 405 (Method Not Allowed) responses for you. If your app relies on that, you can add a middleware function that restricts methods, like the one in the starter kit that we'll look at below.

Get Started in Minutes

Getting started is simple! The quickest way is the Fastly Compute Hono starter kit, which gives you a TypeScript project that's already set up for Compute, with some common patterns wired up for you. If you've used npm create @fastly/compute before (I covered it in this blog, Start Your Next Fastly Compute JavaScript Application with npm init), this will feel very familiar.

To create a new app from the starter kit, run:

npm create @fastly/compute@latest -- --language=typescript --starter-kit=hono

Then start it up in the local development environment:

npm run start

When you're ready, deploy it to Fastly. If you don't have a service yet, you'll be prompted to create one:

npm run deploy

Prefer the Fastly CLI? This works too:

fastly compute init --from=https://github.com/fastly/compute-starter-kits/tree/main/starter-kits/javascript/typescript-hono

Along the way, you'll find that the starter kit already includes:

  • TypeScript source with a tsconfig.json pre-configured for Compute

  • The @fastly/hono-fastly-compute helper library

  • Route matching with Hono

  • HTTP method restrictions

  • Static file embedding with includeBytes

  • Logging to a Fastly endpoint

  • Backend fetch with CacheOverride

You can also find the source on GitHub.

Code examples

Bindings: Fastly resources on c.env

Hono itself isn't a Fastly product, so the glue between it and Compute is the @fastly/hono-fastly-compute package, an adapter package that Fastly also provides. This is the part of the integration that's unique to Compute. Fastly resources such as backends, loggers, KV Stores, Config Stores, Secret Stores, and ACLs normally have to be opened by name wherever you need them. With the adapter's buildFire helper, you declare them once, up front, and Hono hands them to every handler and middleware on c.env, fully typed, so your editor can help you out with autocompletion. Resources are looked up the first time you use them, and cached after that.

A binding is just a name and a resource type. For example, content: "KVStore:page_content" binds a KV Store, and secrets: "SecretStore:api_secrets" binds a Secret Store. Config Stores, ACLs, and environment variables are bound the same way. The key is the name you'll use on c.env. If it's the same as the name of the resource, you can leave off the colon and write just the type, as in assets: "KVStore". Otherwise, add the real name after the colon, which also helps when the name isn't a valid JavaScript identifier.

Here's an app that puts a few of them to work:

import { Hono } from "hono";
import { buildFire } from "@fastly/hono-fastly-compute";

const fire = buildFire({
  content: "KVStore:page_content",
  config: "ConfigStore:site_config",
  secrets: "SecretStore:api_secrets",
  origin: "Backend:my_origin",
});

const app = new Hono<{ Bindings: typeof fire.Bindings }>();

// KV Store: serve a page that's stored at the edge
app.get("/pages/:slug", async (c) => {
  const entry = await c.env.content.get(c.req.param("slug"));
  if (!entry) {
    return c.notFound();
  }
  return c.html(await entry.text());
});

// Config Store: change behavior without redeploying
app.get("/banner", (c) => {
  const message = c.env.config.get("banner_message");
  return c.json({ message });
});

// Secret Store: keep an API key out of your code
app.get("/weather", async (c) => {
  const apiKey = await c.env.secrets.get("weather_api_key");
  if (!apiKey) {
    return c.text("Missing API key", 500);
  }
  return fetch("https://api.example.com/weather", {
    backend: c.env.origin,
    headers: { Authorization: `Bearer ${apiKey.plaintext()}` },
  });
});

fire(app);

If a resource doesn't exist, or isn't linked to your service, its binding is undefined, so it's worth checking before you use it. One more thing to watch for: Config Store names can only contain letters, digits, and underscores, so a store called my-config can't be opened.

The adapter has a couple more things to offer. clientInfo and serverInfo are always available on c.env, even if you don't define any bindings of your own. There are also a few small helpers. getConnInfo() is Fastly Compute's implementation of Hono's ConnInfo helper, and logFastlyServiceVersion() is a middleware that logs the service version, which comes in handy when you're trying to work out which version of your service handled a request. If you don't have any resources of your own to bind, you can import fire directly:

import { Hono } from "hono";
import {
  fire,
  getConnInfo,
  logFastlyServiceVersion,
} from "@fastly/hono-fastly-compute";

const app = new Hono();

app.use("*", logFastlyServiceVersion());

app.get("/whoami", (c) => {
  const info = getConnInfo(c);
  return c.text(`Your remote address is ${info.remote.address}`);
});

fire(app);

A quick note: @fastly/hono-fastly-compute is provided as a Fastly Labs product, so see the Fastly Labs site for terms of use. It works with @fastly/js-compute ^3.33.0 or ^4.0.0 and hono ^4.5.0. The starter kit takes care of setting these up for you.

Middleware: Restrict HTTP Methods

Middleware works just the way you'd expect coming from Express. This example, taken from the starter kit, rejects any request whose method isn't HEAD, GET, or PURGE:

import { createMiddleware } from "hono/factory";

app.use(
  createMiddleware(async (c, next) => {
    if (!["HEAD", "GET", "PURGE"].includes(c.req.method)) {
      return c.text("This method is not allowed", 405);
    }
    await next();
  })
);

Fetching from an Origin with a Cache Override

Calling a backend is just a fetch, with Compute's backend and cacheOverride options added in:

import { CacheOverride } from "fastly:cache-override";

app.get("/api/*", async (c) => {
  const cacheOverride = new CacheOverride("override", { ttl: 60 });
  return fetch(c.req.raw, {
    backend: c.env.origin,
    cacheOverride,
  });
});

Serving Static Files

Express has express.static() for serving files from a directory. Compute doesn't have a filesystem to serve from, so static files take a different route. You publish them to a KV Store with Fastly's Compute static publisher, and your app serves them from there. Starting with version 8.1, the static publisher comes with Hono middleware of its own, so serving those files looks just like it would in any other Hono app:

import { Hono } from "hono";
import { fire } from "@fastly/hono-fastly-compute";
import { fromStaticPublishRc } from "@fastly/compute-js-static-publish/hono";
import rc from "../static-publish.rc.js";

const { serveStatic, serveFallback } = fromStaticPublishRc(rc);
const app = new Hono();

// Your own routes go before the static files
app.get("/api/hello", (c) => c.json({ hello: "world" }));

// Serve the published files. If no file matches, the request moves on.
app.use("*", serveStatic());

// When nothing matches, serve your SPA file or 404 page.
app.notFound(serveFallback());

fire(app);

See the static publisher's documentation for how to set up static-publish.rc.js and publish your files.

If no file matches, serveStatic() passes the request on, so routes after it still get their requests, and serveFallback() serves your single-page app file or your 404 page when nothing else does. The static publisher can even generate a Hono app like this one for you, with its new hono template. I'll show how in an upcoming post.

Community Middleware

And this is where Hono's popularity really pays off. Hono includes a good set of built-in middleware, and the community publishes plenty more, so instead of writing common functionality yourself, you can add it with a single app.use() call:

import { cors } from "hono/cors";
import { logger } from "hono/logger";

app.use("*", logger());
app.use("/api/*", cors());

Build with a Coding Agent

These days, a lot of us build with the help of a coding agent, and Hono is a great fit for that. It's small, typed, and widely used, so there are plenty of well-established conventions for an agent to follow. And the starter kit gives it a working project to build on, rather than an empty directory.

Want to give it a try? Paste this prompt into your coding agent of choice:

Create a new Fastly Compute app using the Hono starter kit:

  npm create @fastly/compute@latest -- --language=typescript --starter-kit=hono

Then extend src/index.ts to add:

1. GET /hello/:name that returns a JSON greeting for the given name.
2. A middleware that adds an "X-Powered-By: Hono on Fastly Compute" header
   to every response.
3. A custom 404 response using app.notFound().
4. A custom error response using app.onError().

Keep the code in TypeScript, follow the patterns already used in the starter
kit, and run it locally with `npm run start` to confirm each route works.
Summarize the changes you made when you're done.

From there, just keep going in plain language. Ask your agent to proxy /api/* to your own backend, add caching with CacheOverride, or pull in some community middleware, and see how far you get.

Join the Discussion

Whether you're new to Compute or coming from Express, Hono is a quick way to get a typed, production-ready service running at the edge. Here's where to start:

I’m excited to see what you build with Hono on Compute! If you haven't already, get your free Fastly developer account and join us on the Fastly community forum. The team would love to hear about what you've been building.

Happy coding!

Sind Sie bereit, loszulegen?

Treten Sie noch heute mit uns in Kontakt