Katman

Server

Start your API with serve(), deploy anywhere with handler(), enable HTTP/2, and auto-generate API docs.

Katman gives you two ways to run your API: serve() for a quick Node.js server, and handler() for any runtime that supports the Fetch API (Bun, Deno, Cloudflare Workers, etc.).

serve()

The simplest way to get a server running. One call, and you have an HTTP server with automatic port selection, optional API docs, and WebSocket support:

import {  } from "katman"
import {  } from "zod"

const  = ({
  : () => ({ : getDB() }),
})

const  = .({
  : .(() => ({ : "ok" })),
})

.(, {
  : 3000,
})

Run it with npx tsx src/server.ts and you'll see:

Katman server running at http://127.0.0.1:3000

All options

k.serve(appRouter, {
  : 3000,               // auto-finds next available if busy
  : "0.0.0.0",      // bind to all interfaces
  : true,             // API docs at /reference
  : true,                 // WebSocket RPC on the same port
  : {                  // HTTP/2 with TLS
    : "./certs/cert.pem",
    : "./certs/key.pem",
  },
})
OptionTypeDefaultDescription
portnumber3000Port to listen on. If it's taken, Katman automatically picks the next free port in 3000-3100.
hostnamestring"127.0.0.1"Network interface. Use "0.0.0.0" to accept connections from other machines.
scalarboolean | ScalarOptionsfalseEnable auto-generated API docs at /reference.
wsbooleanfalseEnable WebSocket RPC on the same port.
http2{ cert, key }undefinedEnable HTTP/2 with TLS certificates. Falls back to HTTP/1.1 for older clients.

Automatic port selection

If your requested port is already in use, serve() finds the next available one in the 3000-3100 range. You never need to handle EADDRINUSE yourself.

handler()

For runtimes other than Node.js, or when you want to plug Katman into an existing server, use handler(). It returns a standard Fetch API function: (Request) => Promise<Response>.

const  = k.handler(appRouter)
// handle is: (request: Request) => Promise<Response>

This works everywhere the Web Fetch API exists:

const  = k.handler(appRouter)

Bun.serve({
: 3000,
: ,
})
const  = k.handler(appRouter)

Deno.serve({ : 3000 }, )
const  = k.handler(appRouter)

export default {
: ,
}

handler() supports content negotiation automatically. If the client sends an Accept: application/x-msgpack header, the response is encoded as MessagePack. Same for devalue. JSON is the default fallback.

Content negotiation

Both serve() and handler() inspect the Accept header and respond in the format the client prefers:

Accept headerResponse formatWhen to use
application/json (or none)JSONDefault, works everywhere
application/x-msgpackMessagePackSmaller payloads, binary
application/x-devalue+jsondevalueRich types (Date, Map, Set, BigInt)

The server also checks Content-Type on incoming POST requests to decode the body correctly. No configuration needed on the server side — it all happens automatically.

Scalar API docs

Katman can generate an OpenAPI 3.1.0 spec from your router and serve an interactive API reference powered by Scalar:

k.serve(appRouter, {
  : 3000,
  : true,
})

This gives you two extra routes:

  • /reference — interactive API documentation UI
  • /openapi.json — the raw OpenAPI specification

The spec is generated once at startup, so there is no per-request cost.

Customizing the docs

Pass an options object instead of true:

k.serve(appRouter, {
  : {
    : "My API",
    : "Built with Katman",
    : "2.0.0",
    : [{ : "https://api.example.com" }],
    : { : "[email protected]" },
    : { : "http", : "bearer", : "JWT" },
  },
})

Adding metadata to procedures

The generated docs pull information from your procedure definitions. Add route metadata to make the docs more useful:

const  = k.query({
  : z.object({ : z.number().optional() }),
  : {
    : "List all users",
    : "Returns a paginated list of users, ordered by creation date.",
    : ["users"],
  },
  : ({ ,  }) => .db.users.findMany({ : .limit }),
})

The route field accepts:

PropertyDescription
summaryShort description shown in the endpoint list
descriptionLonger description shown in the detail view
tagsGroup endpoints by tag
deprecatedMark an endpoint as deprecated
successStatusOverride the default 200 status
successDescriptionDescribe what a successful response looks like

HTTP/2

For production deployments that benefit from multiplexing and header compression, pass TLS certificates:

k.serve(appRouter, {
  : 443,
  : {
    : "./certs/cert.pem",
    : "./certs/key.pem",
  },
})

Output:

Katman server running at https://127.0.0.1:443
  HTTP/2 enabled (with HTTP/1.1 fallback)

HTTP/2 requires TLS. Older clients that don't support HTTP/2 automatically fall back to HTTP/1.1 on the same port.

For local development, generate self-signed certificates with mkcert. For production, use certificates from your hosting provider or Let's Encrypt.

WebSocket support

Enable bidirectional RPC alongside the HTTP server:

k.serve(appRouter, {
  : 3000,
  : true,
})
Katman server running at http://127.0.0.1:3000
  WebSocket RPC at ws://127.0.0.1:3000

HTTP and WebSocket share the same port. The server detects WebSocket upgrade requests and routes them accordingly. See the WebSocket protocol page for the message format and how to connect from the client.

Lifecycle hooks

Katman fires hooks at key points during request processing. Register them in the hooks option when creating the instance:

const  = katman({
  : () => ({ : getDB() }),
  : {
    : ({ ,  }) => {
      .(`--> ${}`)
    },
    : ({ , ,  }) => {
      .(`<-- ${} (${.toFixed(1)}ms)`)
    },
    : ({ ,  }) => {
      .(`ERR ${}:`, )
    },
    "serve:start": ({ , ,  }) => {
      .(`Server ready at ${}`)
    },
  },
})

You can also add or remove hooks after the instance is created:

// Add a hook
k.hook("error", ({  }) => reportToSentry())

// Remove a hook
k.removeHook("error", myHookFn)
HookWhen it firesPayload
requestBefore a request is processed{ path, input }
responseAfter a successful response{ path, output, durationMs }
errorWhen any error occurs{ path, error }
serve:startWhen the server starts listening{ url, port, hostname }

Hooks are for side effects like logging and metrics. They don't modify the request or response. For that, use guards and wraps.

callable()

For server-side code where you need to call a procedure directly — without HTTP, serialization, or the client proxy. Useful in scripts, cron jobs, and seed files.

import {  } from "katman"

const  = k.query(
  z.object({ : z.number().optional() }),
  ({ ,  }) => .db.users.findMany({ : .limit }),
)

const  = (, {
  : () => ({ : getDB() }),
})

// Direct call — compiled pipeline, no HTTP
const  = await ({ : 10 })

The compiled pipeline (guards, wraps, validation) runs exactly as it would through serve() or handler(). The only difference is there's no network involved.

What's next?

  • Client — connect to your server from the browser or another service
  • Middleware — guards and wraps that run inside your request pipeline
  • Fastify integration — mount Katman inside an existing Fastify app
  • Plugins — add CORS, logging, rate limiting, and tracing
  • Protocols — learn about JSON, MessagePack, devalue, and WebSocket

On this page