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

tyex

v0.14.0

Published

Type-safe Express.js routes with automatic OpenAPI documentation generation.

Readme

tyex

Type Safety Layer for Express APIs
Runtime Validation • OpenAPI Docs • Full Type Inference

npm license codecov CI

Why tyex?

Building Express APIs involves three tedious, duplicated tasks:

  • Type definitions for your request/response objects
  • Runtime validation to ensure incoming data is valid
  • API documentation for consumers to understand your endpoints

Keeping these in sync is a maintenance nightmare. Instead of juggling multiple libraries and duplicating schemas, tyex lets you define everything once and get all three benefits automatically.

Features

  • 🔄 Single source of truth for types, validation, and documentation
  • 🚀 No new frameworks to learn - it's just Express
  • 🔍 Full TypeScript inference for request params, query, and body
  • Runtime validation with automatic coercion (strings to numbers, etc.)
  • 📚 OpenAPI documentation auto-generated from your handlers
  • 🔌 Async handler support with proper error handling

Installation

npm install tyex @sinclair/typebox

Quick Start

import express from "express";
import tyex from "tyex";
import { Type } from "@sinclair/typebox";
import swaggerUi from "swagger-ui-express";

const app = express();
app.use(express.json());

// Define your schema with TypeBox
const UserSchema = Type.Object({
  id: Type.Integer(),
  username: Type.String(),
});

// Create a route with tyex.handler
app.get(
  "/api/users/:id",
  tyex.handler(
    {
      parameters: [
        {
          name: "id",
          in: "path",
          required: true,
          schema: Type.Integer(),
        },
      ],
      responses: {
        "200": {
          description: "User details",
          content: {
            "application/json": {
              schema: UserSchema,
            },
          },
        },
      },
    },
    async (req, res) => {
      const user = await getUser(req.params.id);
      res.json(user);
    },
  ),
);

// Add OpenAPI documentation endpoint
app.get("/api-spec", tyex.openapi());

// Optional: Add Swagger UI
app.use(
  "/api-docs",
  swaggerUi.serve,
  swaggerUi.setup(null, { swaggerOptions: { url: "/api-spec" } }),
);

app.listen(3000);

How It Works

Define Routes with OpenAPI Schema

The tyex.handler function wraps your Express handlers with two key benefits:

  1. Type-checking - Your handler receives fully typed request objects
  2. Runtime validation - Incoming requests are validated against your schema
tyex.handler(
  {
    // OpenAPI 3 operation object
    parameters: [...],
    requestBody: {...},
    responses: {...},
  },
  (req, res) => {
    // Your regular Express handler
  }
)

Generating OpenAPI Documentation

Option 1: Using the Middleware

The tyex.openapi() middleware provides a quick way to expose your documentation on a route. It generates the spec on the first request.

// Basic usage
app.get("/api-spec", tyex.openapi());

// With additional configuration
app.get(
  "/api-spec",
  tyex.openapi({
    document: {
      openapi: "3.0.3",
      info: {
        title: "My API",
        version: "1.0.0",
      },
      servers: [
        {
          url: "https://api.example.com",
        },
      ],
    },
  }),
);

Option 2: Programmatic Generation

For more flexibility, you can generate the OpenAPI document directly as a JavaScript object using oasGenerator. This allows you to use the spec in build scripts, tests, or apply complex logic before serving it.

// scripts/build-spec.js
import app from "../src/app";
import tyex from "tyex";
import fs from "fs";

// Generate the document object
const oasDoc = tyex.oasGenerator(app);

// Write it to a file
fs.writeFileSync("./public/openapi.json", JSON.stringify(oasDoc));
console.log("✅ OpenAPI spec generated successfully.");

OpenAPI-Specific Types

Since OpenAPI schemas are a superset of JSON Schema, tyex provides helper functions for common OpenAPI-specific patterns:

import { TypeOpenAPI } from "tyex";

TypeOpenAPI.Nullable(Type.String()); // { type: 'string', nullable: true }
TypeOpenAPI.StringEnum(["admin", "user"]); // enum: ['admin', 'user']
TypeOpenAPI.Options(Type.Number(), { default: 10 }); // Default values with proper type inference

Error Handling

Validation errors are passed to Express's error handling middleware:

import { ValidationError } from "tyex";

app.use((err, req, res, next) => {
  if (err instanceof ValidationError) {
    return res.status(400).json({ errors: err.errors });
  }
  next(err);
});

Complete Examples

See the examples directory for full working examples, including the "kitchen sink" example with authentication, error handling, and more.

Current Limitations

  • Only application/json request bodies are supported currently
  • Response schemas are used for types and documentation, but aren't validated

License

MIT