npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

openapi-ts-router

v0.3.6

Published

Thin wrapper around the router of web frameworks like Express and Hono, offering OpenAPI typesafety and seamless integration with validation libraries such as Valibot and Zod

Readme

Status: Experimental

openapi-ts-router is a thin wrapper around the router of web frameworks like Express and Hono, offering OpenAPI typesafety and seamless integration with validation libraries such as Valibot and Zod.

  • Full type safety for routes, methods, params, body and responses
  • Runtime validation using Zod/Valibot
  • Catches API spec mismatches at compile time
  • Zero manual type definitions needed
  • Seamless integration with existing Express/Hono applications
  • Enforces OpenAPI schema compliance at both compile-time and runtime

📚 Examples

📖 Usage

ExpressJs

openapi-ts-router provides full type-safety and runtime validation for your Express API routes by wrapping a Express router:

Good to Know: While TypeScript ensures compile-time type safety, runtime validation is equally important. openapi-ts-router integrates with Zod/Valibot to provide both:

  • Types verify your code matches the OpenAPI spec during development
  • Validators ensure incoming requests match the spec at runtime
import { Router } from 'express';
import { createExpressOpenApiRouter } from 'openapi-ts-router';
import { zValidator } from 'validation-adapters/zod';
import * as z from 'zod';
import { paths } from './gen/v1'; // OpenAPI-generated types
import { PetSchema } from './schemas'; // Custom reusable schema for validation

export const router: Router = Router();
export const openApiRouter = createExpressOpenApiRouter<paths>(router);

// GET /pet/{petId}
openApiRouter.get('/pet/{petId}', {
	pathValidator: zValidator(
		z.object({
			petId: z.number() // Validate that petId is a number
		})
	),
	handler: (req, res) => {
		const { petId } = req.valid.params; // Access parsed & validated params
		res.send({ name: 'Falko', photoUrls: [] });
	}
});

// POST /pet
openApiRouter.post('/pet', {
	bodyValidator: zValidator(PetSchema), // Validate request body using PetSchema
	handler: (req, res) => {
		const { name, photoUrls } = req.body; // Access validated body data
		res.send({ name, photoUrls });
	}
});

// TypeScript will error if route/method doesn't exist in OpenAPI spec
// or if response doesn't match defined schema

Full example

Hono

openapi-ts-router provides full type-safety and runtime validation for your HonoAPI routes by wrapping a Hono router:

Good to Know: While TypeScript ensures compile-time type safety, runtime validation is equally important. openapi-ts-router integrates with Zod/Valibot to provide both:

  • Types verify your code matches the OpenAPI spec during development
  • Validators ensure incoming requests match the spec at runtime

Note: Hono's TypeScript integration provides type suggestions for c.json() based on generically defined response types, but it doesn't enforce these types at compile-time. For example, c.json('') won't raise a type error even if the expected type is { someType: string }. This is due to Hono's internal use of TypedResponse<T>, which infers but doesn't strictly enforce the passed generic type. Hono Discussion

import { Hono } from 'hono';
import { createHonoOpenApiRouter } from 'openapi-ts-router';
import { zValidator } from 'validation-adapters/zod';
import * as z from 'zod';
import { paths } from './gen/v1'; // OpenAPI-generated types
import { PetSchema } from './schemas'; // Custom reusable schema for validation

export const router = new Hono();
export const openApiRouter = createHonoOpenApiRouter<paths>(router);

// GET /pet/{petId}
openApiRouter.get('/pet/{petId}', {
	pathValidator: zValidator(
		z.object({
			petId: z.number() // Validate that petId is a number
		})
	),
	handler: (c) => {
		const { petId } = c.req.valid('param'); // Access validated params
		return c.json({ name: 'Falko', photoUrls: [] });
	}
});

// POST /pet
openApiRouter.post('/pet', {
	bodyValidator: zValidator(PetSchema), // Validate request body using PetSchema
	handler: (c) => {
		const { name, photoUrls } = c.req.valid('json'); // Access validated body data
		return c.json({ name, photoUrls });
	}
});

// TypeScript will error if route/method doesn't exist in OpenAPI spec
// or if response doesn't match defined schema

Full example

❓ FAQ

Why are error types not supported in the response type?

We intentionally only type success responses (2xx) while leaving error responses out. Here’s why:

Errors should be handled via exceptions & middleware
Instead of typing every possible error response inline, we believe that handling errors globally in middleware provides clearer, more maintainable code.
👉 Example: Hono Example (Docs) & Express Example (Docs)

Inline error responses require as any
Since .send() only expects success types, explicit casting is required to enforce an error response:

res.status(500).send({
	code: '#ERR_XYZ',
	message: 'Error Message'
} satisfies TOperationResponseContent<paths['/pet/{petId}']['get'], 500> as any);

Why is the Status Code not inferred?

Express and Hono don't infer status codes for res.send() / c.json()
Since we can’t infer the value of the res.status() / c.json() method call, res.send() / c.json() is typed as a union of success response types. For example, it could be:

{ message: 'Success Body of 200' } | { message: 'Success Body of 201' }

To enforce a specific success type, use satisfies
Example of explicitly enforcing a 201 response type:

res.status(201).send({
	id: 123
} satisfies TOperationResponseContent<paths['/pet/{petId}']['get'], 201>);

Hono c.json() not typesafe?

Hono's TypeScript integration provides type suggestions for c.json() based on generically defined response types, but it doesn't enforce these types at compile-time. For example, c.json('') won't raise a type error even if the expected type is { someType: string }. This is due to Hono's internal use of TypedResponse<T>, which infers but doesn't strictly enforce the passed generic type. Hono Discussion

To enforce a specific success type, use satisfies
Example of explicitly enforcing a 201 response type:

c.json(
	{
		id: 123
	} satisfies TOperationResponseContent<paths['/pet/{petId}']['get'], 201>,
	201
);