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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@contract-first-api/express

v2.0.0

Published

Mount shared API contracts on an Express app with typed handlers and request validation.

Readme

@contract-first-api/express

@contract-first-api/express connects a shared contract tree to an Express app. You give it your contracts and a matching service object, and it registers the routes for you.

What you do with this package

Use it to:

  • mount routes from a shared contract tree
  • validate params, query, and body with the Zod schemas from the contracts
  • keep backend handler inputs and outputs typed from the same source as the frontend
  • add typed request context
  • read contract metadata inside middlewares and createContext

Basic usage

import { createExpressRouter, initServices } from "@contract-first-api/express";
import { contracts } from "@example/shared";
import express from "express";

type ContractMeta = {
  requiresAuth?: boolean;
  auditLabel?: string;
};

type RequestContext = {
  requestId: string;
  viewerId?: string;
};

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

const { defineService, defineMiddleware } = initServices<
  typeof contracts,
  ContractMeta,
  RequestContext
>();

declare global {
  namespace Express {
    interface Request {
      viewerId?: string;
    }
  }
}

const authMiddleware = defineMiddleware((req, _res, next) => {
  if (req.contract.meta?.requiresAuth) {
    req.viewerId = "viewer-123";
  }

  next();
});

const services = {
  health: defineService("health", {
    get({ context }) {
      return {
        status: "ok",
        requestId: context.requestId,
      };
    },
  }),
  todos: defineService("todos", {
    list() {
      return { items: [] };
    },
    create({ title, context }) {
      console.log("viewer", context.viewerId);
      return {
        id: crypto.randomUUID(),
        title,
        createdAt: new Date().toISOString(),
      };
    },
  }),
};

createExpressRouter({
  app,
  contracts,
  services,
  routePrefix: "/api",
  middlewares: [authMiddleware],
  createContext: (req) => ({
    requestId: `${req.contract.meta?.auditLabel ?? "route"}:${crypto.randomUUID()}`,
    viewerId: req.viewerId,
  }),
});

How it works

Each service function receives one object:

  • request fields from the contract
  • context from createContext

Middleware and validation

When you call createExpressRouter:

  • every contract route is registered on the Express app
  • incoming body, query, and params are validated against the contract
  • validated values are merged into req.validatedRequest
  • the current contract is attached to req.contract
  • custom middlewares run after validation and before createContext
  • a failed validation throws RequestValidationError with statusCode = 400
  • static routes are registered before parameter routes when paths overlap

Common setup pattern

A typical backend flow looks like this:

  1. Define contracts in a shared package.
  2. Call initServices<typeof contracts, ContractMeta, RequestContext>() to type the service helpers.
  3. Implement handlers with defineService.
  4. Add metadata-aware Express middleware with defineMiddleware when needed.
  5. Pass app, contracts, and services into createExpressRouter.
  6. Add a routePrefix like /api so the frontend client can target one API base URL.

If you already have an Express app with middleware, keep that setup as-is and call createExpressRouter after the middleware you want the routes to use.