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

@web-ts-toolkit/express-response-handler

v0.2.0

Published

Express response handler

Readme

express-response-handler

FastAPI-style return-value responses for Express.

Instead of calling res.json(...) in every route, return a value. This package turns that return value into a 200 OK JSON response, while still letting you return explicit response wrappers or throw errors when needed.

Installation

npm install @web-ts-toolkit/express-response-handler

Philosophy

Express is usually imperative:

app.get('/users/:id', async (req, res, next) => {
  try {
    const user = await getUser(req.params.id);

    if (!user) {
      return res.status(404).json({ message: 'user not found' });
    }

    return res.json(user);
  } catch (err) {
    next(err);
  }
});

This package lets you write the same route in a more declarative style:

app.get(
  '/users/:id',
  handleResponse(async (req) => {
    const user = await getUser(req.params.id);

    if (!user) {
      throw new NotFoundError('user not found');
    }

    return user;
  }),
);

The main rule is simple:

  • return a plain value for a 200 OK JSON response
  • return an explicit response wrapper for a custom status or format
  • throw an error for failures

Quick Start

import express from 'express';

import apiHandler from '@web-ts-toolkit/express-response-handler';
import { NotFoundError } from '@web-ts-toolkit/http-errors';

const { handleResponse, HttpResponse } = apiHandler;

const app = express();

app.get(
  '/health',
  handleResponse(() => {
    return { ok: true };
  }),
);

app.get(
  '/users/:id',
  handleResponse(async (req) => {
    const user = await getUser(req.params.id);

    if (!user) {
      throw new NotFoundError('user not found');
    }

    return user;
  }),
);

app.post(
  '/jobs',
  handleResponse(async () => {
    const job = await createJob();
    return HttpResponse.created(job);
  }),
);

How It Works

handleResponse(...) wraps one or more Express handlers.

When a handler runs:

  • a plain returned value becomes res.json(value)
  • a returned HttpResponse.*(...) wrapper controls the status code
  • a returned HttpResponse.csv(...) streams CSV
  • a thrown error becomes an error response
  • a returned promise is awaited automatically

Supported forms:

  • handleResponse(fn)
  • handleResponse(fn1, fn2)
  • handleResponse([fn1, fn2])

Examples

Return JSON with 200 OK

app.get(
  '/profile',
  handleResponse(async (req) => {
    return {
      id: req.user.id,
      email: req.user.email,
    };
  }),
);

Return a custom success status

app.post(
  '/sessions',
  handleResponse(async (req) => {
    const session = await createSession(req.body);
    return HttpResponse.created(session);
  }),
);

Throw HTTP errors

import { BadRequestError, NotFoundError } from '@web-ts-toolkit/http-errors';

app.get(
  '/projects/:id',
  handleResponse(async (req) => {
    if (!req.params.id) {
      throw new BadRequestError('project id is required');
    }

    const project = await getProject(req.params.id);

    if (!project) {
      throw new NotFoundError('project not found');
    }

    return project;
  }),
);

Return CSV

app.get(
  '/reports/users.csv',
  handleResponse(async () => {
    const rows = await getUserReportRows();

    return HttpResponse.csv(rows, {
      filename: 'users.csv',
    });
  }),
);

Use more than one Express handler

app.get(
  '/me',
  handleResponse(requireAuth, async (req) => {
    return req.user;
  }),
);

If you call next() with no arguments, Express middleware flow continues normally.

Do not use next(value) for successful responses. Return the value instead.

Hooks

Hooks let you observe or modify response flow without repeating code in every route.

Available setters:

  • apiHandler.preJson = fn
  • apiHandler.postJson = fn
  • apiHandler.preError = fn
  • apiHandler.postError = fn

Example:

apiHandler.preJson = async function (data) {
  console.log('about to send json response', data);
};

apiHandler.preError = async function (err) {
  console.error('request failed', err);
};

Custom Error Messages

Non-HTTP errors default to status 422 with a message resolved from the thrown value.

You can customize that behavior:

apiHandler.errorMessageProvider = function (err) {
  return {
    message: 'request failed',
    detail: err instanceof Error ? err.message : String(err),
  };
};

Structured Error Format

The default error payload is intentionally small:

{ "message": "project not found" }

If you want an AIP-193-inspired error envelope, create a handler instance with errorFormat: 'aip193':

import apiHandler from '@web-ts-toolkit/express-response-handler';
import { ErrorFormats } from '@web-ts-toolkit/express-response-handler';

const structuredHandler = apiHandler.createHandler({
  errorFormat: ErrorFormats.aip193,
  errorDomain: 'api.example.com',
});

That mode returns errors in this shape:

{
  "error": {
    "code": 404,
    "status": "NOT_FOUND",
    "message": "project not found",
    "details": [
      {
        "type": "error_info",
        "reason": "NOT_FOUND",
        "domain": "api.example.com"
      }
    ]
  }
}

You can enrich HTTP errors with machine-readable fields:

import { BadRequestError } from '@web-ts-toolkit/http-errors';

app.get(
  '/projects/:id',
  structuredHandler.handleResponse(async () => {
    throw new BadRequestError('invalid project id', {
      reason: 'INVALID_PROJECT_ID',
      metadata: { field: 'id' },
      details: [
        {
          type: 'help',
          links: [
            {
              description: 'Project ID format guide',
              url: 'https://api.example.com/docs/errors/invalid-project-id',
            },
          ],
        },
      ],
    });
  }),
);

If you want RFC 9457 problem details instead, create a handler instance with errorFormat: 'rfc9457':

import apiHandler from '@web-ts-toolkit/express-response-handler';
import { ErrorFormats } from '@web-ts-toolkit/express-response-handler';

const problemHandler = apiHandler.createHandler({
  errorFormat: ErrorFormats.rfc9457,
  errorDomain: 'api.example.com',
});

That mode returns application/problem+json payloads in this shape:

{
  "type": "https://api.example.com/problems/invalid-project-id",
  "title": "Invalid project id",
  "status": 400,
  "detail": "invalid project id",
  "instance": "/problems/invalid-project-id/123",
  "errors": [
    {
      "detail": "must be a valid project id",
      "pointer": "#/id"
    }
  ]
}

You can enrich HTTP errors with problem detail fields:

import { BadRequestError } from '@web-ts-toolkit/http-errors';

app.get(
  '/projects/:id',
  problemHandler.handleResponse(async () => {
    throw new BadRequestError('invalid project id', {
      type: 'https://api.example.com/problems/invalid-project-id',
      title: 'Invalid project id',
      instance: '/problems/invalid-project-id/123',
      errors: [
        {
          detail: 'must be a valid project id',
          pointer: '#/id',
        },
      ],
    });
  }),
);

Isolated Instances

The default export is a ready-to-use singleton. If you want separate hook configuration per router or module, create an isolated instance:

import apiHandler from '@web-ts-toolkit/express-response-handler';

const adminHandler = apiHandler.createHandler();
const publicHandler = apiHandler.createHandler();

adminHandler.preError = async function (err) {
  console.error('admin route failed', err);
};

When To Use It

This package is a good fit when you want:

  • Express routes that return values instead of calling res.json(...)
  • a small abstraction rather than a full framework
  • consistent JSON, error, and CSV response behavior

It is less useful if you want fully explicit low-level Express response control in every route.