Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 96 ยท TypeScript in Practice

Typed Backends: Fastify, Hono and Koa

Compare Fastify, Hono and Koa in TypeScript - typed route generics, schemas and type providers, context typing, middleware and testing - with runnable stand-ins of each idea.

Express is the default Node.js server, but its types are loose: req.params is a bag of strings, and req.body is any. Newer frameworks were designed after TypeScript became mainstream, and they give you more help. In this lesson you will meet three of them: Fastify (fast, schema driven), Hono (tiny, runs everywhere, end-to-end typed) and Koa (minimal, built around middleware). We compare how each one types routes, request data, shared context and middleware.

None of these frameworks can run in the browser editor, so their real code is read-only. Each section pairs it with a stand-in you can run, a few lines of TypeScript that reproduce the typing idea so you can see why the compiler accepts or rejects your code. If you are choosing between a framework with structure and a minimal one, compare this lesson with TypeScript with NestJS and the Express section of TypeScript with Frameworks.

Fastify: typed routes with generics

Fastify is a high-performance framework that ships its own type definitions. You describe a route with a generic object with up to five keys: Params, Querystring, Body, Headers and Reply.

TypeScript
import Fastify from 'fastify';

const app = Fastify({ logger: true });

interface UserParams {
  id: string;
}
interface UserQuery {
  verbose?: string;
}

app.get<{ Params: UserParams; Querystring: UserQuery; Reply: { id: number; verbose: boolean } }>(
  '/users/:id',
  async (request) => {
    // request.params.id is a string; request.query.verbose is string | undefined
    return { id: Number(request.params.id), verbose: request.query.verbose === 'true' };
  },
);

await app.listen({ port: 3000 });

The handler's return type is checked against Reply, and request.params has exactly the fields you declared. That is the pattern the following stand-in reproduces.

TypeScript Fastify-style route generics: Params, Querystring, Body, Reply

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The key move is that one type argument carries four pieces of information, and every part of the handler is typed from it. Misspell req.params.id and the compiler tells you. The route-matching code in inject is untyped glue, much like the real framework's internals.

Hand-written generics have a weakness: the type and the runtime validation can drift apart. Nothing stops a client from sending ?verbose=maybe. Fastify's answer is JSON Schema validation, and type providers that derive the TypeScript types from the schema, so there is one source of truth:

TypeScript
import Fastify from 'fastify';
import { Type, type TypeBoxTypeProvider } from '@fastify/type-provider-typebox';

const app = Fastify().withTypeProvider<TypeBoxTypeProvider>();

app.post(
  '/todos',
  {
    schema: {
      body: Type.Object({ title: Type.String({ minLength: 1 }), done: Type.Optional(Type.Boolean()) }),
      response: { 201: Type.Object({ id: Type.Number(), title: Type.String() }) },
    },
  },
  async (request, reply) => {
    // request.body is { title: string; done?: boolean }, validated before this runs
    reply.code(201);
    return { id: 1, title: request.body.title };
  },
);

There are type providers for TypeBox, json-schema-to-ts and Zod. Compare that to Validating Data with Zod: the idea is the same, an inferred type from a schema.

Two more Fastify features matter in TypeScript projects:

  • Decorators and module augmentation. app.decorateRequest('user', null) adds a property, and you tell TypeScript about it by merging into Fastify's interfaces: declare module 'fastify' { interface FastifyRequest { user: User | null } }.
  • app.inject() sends a fake request through the whole stack without opening a port, which makes tests fast: const res = await app.inject({ method: 'GET', url: '/users/42' }).

Koa: middleware and typed state

Koa is tiny. It has no router, no body parser and no validation; it gives you a context object and an async middleware pipeline. The core idea is the "onion": each middleware runs code, calls await next() to let everything downstream run, then continues with code that executes on the way out.

TypeScript
import Koa from 'koa';

interface AppState {
  user?: { name: string };
}

const app = new Koa<AppState>();

app.use(async (ctx, next) => {
  const started = Date.now();
  await next();
  ctx.set('X-Response-Time', `${Date.now() - started}ms`);
});

app.use(async (ctx) => {
  ctx.body = { hello: ctx.state.user?.name ?? 'stranger' };
});

app.listen(3000);

The generic Koa<StateT, ContextT> is how you type ctx.state and any properties other middleware adds. Install @types/koa for the declarations (and @types/koa__router or @koa/router types for routing). The weak points are ctx.body, which is loosely typed (any), and ctx.request.body, which only exists once a body-parser middleware adds it. You usually need to add a declaration or validate it yourself.

Here is the whole Koa idea, including the composition function, in a runnable stand-in:

TypeScript Koa-style onion middleware with typed state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Read the log. timing wrote "before", then everything else ran inside its await next(), and only afterward did it write "after" with the final status. The errors middleware sits outside the router, so the router's throw became a 500 response instead of crashing the server. That ordering, outer to inner, is the part of Koa worth learning; the typing is just the State generic threaded through.

One compile-time subtlety: ctx.state.user is optional, so the router must check it before reading name. The ?. and the role !== 'admin' test both narrow the type (see Narrowing).

Hono: tiny, portable and end-to-end typed

Hono is built on the Web Standards Request and Response objects, so the same app runs on Node.js, Bun, Deno, Cloudflare Workers and other runtimes. It is written in TypeScript and leans on inference harder than the others. Variables set by middleware are declared in the app's generic:

TypeScript
import { Hono } from 'hono';
import { createMiddleware } from 'hono/factory';

type AppEnv = {
  Variables: {
    requestId: string;
    user: { id: number; name: string };
  };
};

const withUser = createMiddleware<AppEnv>(async (c, next) => {
  c.set('user', { id: 7, name: 'Grace' });
  await next();
});

const app = new Hono<AppEnv>();

app.use('*', withUser);

app.get('/me', (c) => {
  const user = c.get('user');       // { id: number; name: string }
  return c.json({ hello: user.name });
});

export default app;

c.set and c.get check both the key and the value type. Run the stand-in to see that idea in isolation:

TypeScript Hono-style typed context variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The real Hono has two more tricks that make it stand out:

  • Validators. app.post('/todos', zValidator('json', todoSchema), (c) => { const todo = c.req.valid('json'); ... }) validates the body with Zod (from @hono/zod-validator), and todo is typed from the schema.
  • The RPC client. If you export type AppType = typeof app, a client created with hc<AppType>('https://api.example.com') knows every route, parameter and response type: const res = await client.users[':id'].$get({ param: { id: '42' } }). A change on the server becomes a compile error in the client, with no code generation.

Hono also works at the edge, where bundle size matters; its core is a few kilobytes.

Choosing between them

Fastify Hono Koa
Best at Throughput, JSON Schema validation, plugin ecosystem Portability (Node, Bun, Deno, Workers), end-to-end types Minimal core, middleware composition
Route typing Generics or schema type providers Inferred from handlers and validators Add-on router, looser types
Request data request.params/query/body typed by generic or schema c.req.valid('json') after a validator ctx.params (router), ctx.request.body needs a parser
Shared state Decorators plus module augmentation Variables generic on Hono Koa<StateT, ContextT> generics
Testing app.inject() app.request('/path') supertest
Opinionated structure Moderate (plugins, encapsulation) Low None

A practical rule: pick Fastify for a classic Node API where validation and speed matter, Hono when you deploy to edge runtimes or want a typed client, and Koa when you want to assemble the stack yourself (or inherit an existing Koa app). If you need an enterprise-style architecture with dependency injection, look at NestJS, which can even run on top of Fastify.

Habits that apply to every framework

  • Never trust a type argument alone. Body: { title: string } is a promise to the compiler; the client can send anything. Validate with a schema at the boundary (see Typing APIs).
  • Keep a single source of truth for each payload: schema first, type inferred from it.
  • Type your errors. Define an error class with a status code and let one handler convert it to a response, as in the Express error-handling section of TypeScript with Frameworks.
  • Export the app, not the server. Create the app in one file and call listen in another, so tests can use inject() or request() without opening ports.
  • Enable strict and avoid any in handlers; a typed request that silently becomes any loses all the safety.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In Fastify, what does app.get<{ Params: { id: string }; Reply: number }>('/x/:id', handler) give you?

    The generic only affects types. Validation requires a JSON Schema or a type provider.
  2. 2. What is the main purpose of a Fastify type provider such as TypeBox's?

    The schema validates at runtime, and the provider infers the static types from the same schema.
  3. 3. In Koa, what happens to code after await next() in a middleware?

    Koa middleware nest like an onion; the code after next() runs on the way back out.
  4. 4. How does Hono type values shared between middleware and handlers?

    new Hono<{ Variables: ... }>() makes c.get('user') and c.set('user', ...) type checked.
  5. 5. What does exporting type AppType = typeof app enable in Hono?

    The client reads your route types, so server changes show up as compile errors in client code.

Summary

  • Fastify types routes with a generic of Params, Querystring, Body, Headers and Reply, and can infer them from schemas with a type provider.
  • Koa is a minimal onion-style middleware pipeline; Koa<StateT, ContextT> types shared state.
  • Hono types context variables with Hono<{ Variables: ... }>, validates input with validator middleware and offers a typed RPC client.
  • A type argument is a promise to the compiler, not validation: check untrusted input at runtime.
  • Export the app separately from the server so tests can inject requests.
  • Choose by need: Fastify for performance and schemas, Hono for portability and typed clients, Koa for a bare-bones core.

Next: Project: Typed Calculator