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

serverstruct

v2.2.0

Published

Type safe and modular servers with H3

Downloads

1,086

Readme

Serverstruct

⚡️ Typesafe and modular servers with H3.

Serverstruct provides simple helpers for building modular H3 applications with dependency injection using getbox.

Integrations

  • OpenAPI - Typesafe OpenAPI operations with Zod schema validation.
  • OpenTelemetry - Distributed tracing middleware for HTTP requests.

Installation

npm i serverstruct h3 getbox

Quick Start

import { application, serve } from "serverstruct";

const app = application((app) => {
  app.get("/", () => "Hello world!");
});

serve(app, { port: 3000 });

Application

application() creates an H3 instance. A Box instance is created for the application and available as the second argument to the function.

You can mount other apps using app.mount():

import { H3 } from "h3";
import { application, serve } from "serverstruct";

class UserStore {
  public users: User[] = [];

  add(user: User) {
    this.users.push(user);
    return user;
  }
}

// Create an application
const usersApp = application((app, box) => {
  const store = box.get(UserStore);

  app.get("/", () => store.users);
});

// Mount in another app
const app = application((app) => {
  app.get("/", () => "Hello world!");
  app.mount("/users", usersApp);
});

serve(app, { port: 3000 });

When mounting a sub-app, all routes will be added with base prefix and global middleware will be added as one prefixed middleware.

Both application() and controller() can return a custom H3 instance:

import { H3 } from "h3";

const customApp = application(() => {
  const app = new H3({
    onError: (error, event) => {
      console.error("Error:", error);
    },
  });
  app.get("/", () => "Hello from custom app!");
  return app;
});

Note: Sub-app options and global hooks are not inherited when mounted consider setting them in the main app directly.

Controllers

Controllers are apps that are initialized with a parent Box instance, sharing the same dependency container. Use controller() to create H3 app constructors:

import { application, controller } from "serverstruct";

// Create a controller
const usersController = controller((app, box) => {
  const store = box.get(UserStore);

  app.get("/", () => store.users);
  app.post("/", async (event) => {
    const body = await readBody(event);
    return store.add(body);
  });
});

// Use it in your main app
const app = application((app, box) => {
  const store = box.get(UserStore);

  app.get("/count", () => ({
    users: store.users.length,
  }));
  app.mount("/users", box.get(usersController));
});

serve(app, { port: 3000 });

Handlers

Use handler() to create H3 handler constructors:

import { application, handler } from "serverstruct";

// Define a handler
const getUserHandler = handler((event, box) => {
  const store = box.get(UserStore);

  const id = event.context.params?.id;
  return store.users.find((user) => user.id === id);
});

// Use it in your app
const app = application((app, box) => {
  app.get("/users/:id", box.get(getUserHandler));
});

Event Handlers

Use eventHandler() to create H3 handler constructors with additional options like meta and middleware:

import { application, eventHandler } from "serverstruct";

// Define an event handler with additional options
const getUserHandler = eventHandler((box) => ({
  handler(event) {
    const store = box.get(UserStore);

    const id = event.context.params?.id;
    return store.users.find((user) => user.id === id);
  },
  meta: { auth: true },
  middleware: [],
}));

// Use it in your app
const app = application((app, box) => {
  app.get("/users/:id", box.get(getUserHandler));
});

Middleware

Use middleware() to create H3 middleware constructors:

import { application, middleware } from "serverstruct";

class Logger {
  log(message: string) {
    console.log(message);
  }
}

// Define a middleware
const logMiddleware = middleware((event, next, box) => {
  const logger = box.get(Logger);
  logger.log("Request received");
});

// Use it in your app
const app = application((app, box) => {
  app.use(box.get(logMiddleware));
  app.get("/", () => "Hello world!");
});

All middlewares defined with app.use() are global and execute before the matched handler in the exact order they are added to the app.

Error Handling

Error handlers are middleware that catch errors thrown by await next().

The last error handler defined executes before earlier ones. The error bubbles through each error handler until a response is returned or the default error response is sent.

You can return or throw errors from handlers, but only HTTPError will be exposed to the client. All other errors produce a generic 500 response.

Use H3's onError helper to define error handlers:

import { onError } from "h3";
import { application } from "serverstruct";

const app = application((app) => {
  app.use(
    onError((error) => {
      console.log("Error:", error);
    }),
  );
  app.get("/", () => {
    throw new Error("Oops");
  });
});

When the error handler needs access to the Box, wrap it with middleware():

import { onError } from "h3";
import { application, middleware } from "serverstruct";

const errorHandler = middleware((event, next, box) => {
  return onError((error) => {
    console.log("Error:", error);
  });
});

const app = application((app, box) => {
  app.use(box.get(errorHandler));
  app.get("/", () => {
    throw new Error("Oops");
  });
});

Not Found Routes

To catch not found routes, define a catch-all handler and return the desired error:

import { HTTPError } from "h3";

const app = application((app) => {
  app.get("/", () => "Hello world!");
  app.all("**", () => new HTTPError({ status: 404, message: "Not found" }));
});

Mounted apps can define their own not found handlers:

const usersApp = application((app) => {
  app.get("/", () => ["Alice", "Bob"]);
  app.all(
    "**",
    () => new HTTPError({ status: 404, message: "User route not found" }),
  );
});

const app = application((app) => {
  app.mount("/users", usersApp);
  app.all("**", () => new HTTPError({ status: 404, message: "Not found" }));
});

Box Instance

By default, application() creates a new Box instance. Pass a Box instance to reuse it:

import { Box } from "getbox";
import { application, serve } from "serverstruct";

const box = new Box();

const app = application((app, box) => {
  const store = box.get(UserStore);

  app.get("/count", () => store.users.length);
  app.mount("/users", usersApp);
}, box);

serve(app, { port: 3000 });

If you need to pass a custom Box instance to an application it may be better to use a controller instead, which is also easier to test.

// app.ts
import { Box } from "getbox";
import { controller, serve } from "serverstruct";

export const appController = controller((app) => {
  const store = box.get(UserStore);

  app.get("/count", () => store.users.length);
  app.mount("/users", usersApp);
});

const box = new Box();
const app = box.get(appController);

serve(app, { port: 3000 });

Context

context() creates a request-scoped, type-safe store for per-request values.

import { application, context } from "serverstruct";

interface User {
  id: string;
  name: string;
}

// Create a context store
const userContext = context<User>();

const app = application((app) => {
  // Set context in middleware
  app.use((event) => {
    const user = { id: "123", name: "Alice" };
    userContext.set(event, user);
  });

  // Access context in handlers
  app.get("/profile", (event) => {
    // returns undefined if not set
    const maybeUser = userContext.lookup(event);

    // throws if not set
    const user = userContext.get(event);

    return { profile: user };
  });
});

Context Methods

  • set(event, value) - Store a value for the current request
  • get(event) - Retrieve the value for the current request (throws if not found)
  • lookup(event) - Retrieve the value or undefined if not found