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

@alt-stack/server-express

v0.4.3

Published

Type-safe server framework built on Express with Zod validation

Readme

@alt-stack/server-express

A lightweight, type-safe server framework built on Express with Zod validation. Inspired by tRPC's builder pattern, providing full type inference from a central router definition.

Documentation

📚 Full documentation is available at: Server Framework Docs

Installation

pnpm add @alt-stack/server-express express zod
# or
npm install @alt-stack/server-express express zod
# or
yarn add @alt-stack/server-express express zod

For TypeScript users:

pnpm add -D @types/express

Peer Dependencies

  • express: ^4.0.0 || ^5.0.0 - The underlying HTTP framework
  • zod: ^4.0.0 - For schema validation and type inference

Quick Start

import { init, createServer, router } from "@alt-stack/server-express";
import { z } from "zod";

// Initialize with optional custom context
const factory = init<{ user: { id: string } | null }>();

// Create a router with type-safe procedures
const appRouter = router({
  "/users/{id}": factory.procedure
    .input({
      params: z.object({ id: z.string() }),
    })
    .output(z.object({
      id: z.string(),
      name: z.string(),
      email: z.string(),
    }))
    .get(({ input }) => ({
      id: input.params.id,
      name: "Alice",
      email: "[email protected]",
    })),

  "/users": {
    get: factory.procedure
      .output(z.array(z.object({ id: z.string(), name: z.string() })))
      .handler(() => [{ id: "1", name: "Alice" }]),

    post: factory.procedure
      .input({
        body: z.object({
          name: z.string(),
          email: z.string().email(),
        }),
      })
      .output(z.object({ id: z.string() }))
      .handler(({ input }) => ({ id: crypto.randomUUID() })),
  },
});

// Create server with context
const app = createServer(
  { api: appRouter },
  {
    createContext: (req, res) => ({
      user: getUserFromRequest(req.headers.authorization),
    }),
  }
);

// Start the server
app.listen(3000, () => {
  console.log("Server running on http://localhost:3000");
});

Features

  • Type-safe routes: Full TypeScript inference from Zod schemas
  • Builder pattern: Fluent API for defining routes with .get(), .post(), etc.
  • Result-based error handling: Use ok() and err() for explicit error returns
  • Reusable procedures: Create middleware chains with context extension
  • Router combination: Nest routers for modular API design
  • Validation: Automatic Zod validation for params, query, and body
  • OpenAPI generation: Built-in Swagger UI with createDocsRouter()
  • Native Express context: Access full Express API via ctx.express

Error Handling

Use ok() and err() from the Result pattern for type-safe error handling:

import { ok, err } from "@alt-stack/server-express";

const userRouter = router({
  "/users/{id}": factory.procedure
    .input({ params: z.object({ id: z.string() }) })
    .output(z.object({ id: z.string(), name: z.string() }))
    .errors({
      404: z.object({
        error: z.object({ code: z.literal("NOT_FOUND"), message: z.string() }),
      }),
    })
    .get(({ input }) => {
      const user = findUser(input.params.id);
      if (!user) {
        return err({
          _httpCode: 404 as const,
          data: { error: { code: "NOT_FOUND" as const, message: "User not found" } },
        });
      }
      return ok(user);
    }),
});

See @alt-stack/result for full Result type documentation.

Context Access

In handlers and middleware, access the Express request/response via ctx.express:

.get(({ ctx }) => {
  // Access Express req/res directly
  const url = ctx.express.req.url;
  const headers = ctx.express.req.headers;

  // For most cases, just return data (auto-serialized to JSON)
  return { message: "Hello" };
})

OpenAPI Documentation

Generate and serve OpenAPI docs:

import { createDocsRouter, createServer } from "@alt-stack/server-express";

const docsRouter = createDocsRouter(
  { api: appRouter },
  { title: "My API", version: "1.0.0" }
);

const app = createServer({ api: appRouter });

// Mount docs router (returns native Express router)
app.use("/docs", docsRouter);

Input Type Constraints

Since HTTP path parameters and query strings are always strings, input.params and input.query schemas must accept string input:

| Schema | Allowed in params/query? | |--------|--------------------------| | z.string() | ✅ | | z.enum(["a", "b"]) | ✅ | | z.coerce.number() | ✅ | | z.string().transform(...) | ✅ | | z.number() | ❌ compile error | | z.boolean() | ❌ compile error |

// ✅ Valid
.input({
  params: z.object({ id: z.string() }),
  query: z.object({ page: z.coerce.number() }),
})

// ❌ Compile error
.input({
  params: z.object({ id: z.number() }), // Error!
})

Differences from Hono Adapter

| Feature | server-hono | server-express | |---------|-------------|----------------| | Context access | ctx.hono | ctx.express.req / ctx.express.res | | DocsRouter | Returns Router | Returns Express.Router | | Response handling | Web Response API | Express res methods |

Related Packages

License

MIT