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

@travetto/web-http

v8.0.3

Published

Web HTTP Server Support

Readme

Web HTTP Server Support

Web HTTP Server Support

Install: @travetto/web-http

npm install @travetto/web-http

# or

yarn add @travetto/web-http

This module provides basic for running http. https and http2 servers, along with support for tls key generation during development.

CLI - web:http

By default, the framework provides a default @CliCommand for WebHttpServer that will follow default behaviors, and spin up the server.

Terminal: Help for web:http

$ trv web:http --help

Usage: web:http [options]

Description:
  Start the configured web HTTP server for a module.

  Initializes registry and server bindings, supports restart-aware development
  flags, and can attempt to clear conflicting port owners in local workflows.

Options:
  -p, --port <number>                          Port to run on
  --kill-conflict, --no-kill-conflict          Kill conflicting port owner (default: true)
  -m, --module <module>                        Module to run for
  --profile <string>                           Application profiles
  --restart-on-change, --no-restart-on-change  Should the invocation automatically restart on source changes (default: true)
  -d, --debug-ipc                              Should the invocation support debugging via IPC (e.g. from VSCode)
  --help                                       display help for command

Examples:
  Starting a web server on port 8000
    trv web:http -m <MODULE> -p 8000

Running a Server

Terminal: Standard application

$ trv web:http

Initialized {
  manifest: {
    main: {
      name: '@travetto-doc/web-http',
      folder: './doc-exec'
    },
    workspace: {
      name: '@travetto-doc/web-http',
      path: './doc-exec',
      mono: false,
      manager: 'npm'
    }
  },
  runtime: {
    production: false,
    role: 'doc',
    debug: false,
    resourcePaths: [
      './doc-exec/resources'
    ],
    profiles: []
  },
  config: {
    sources: [ { priority: 999, source: 'memory://override' } ],
    active: {
      AcceptConfig: { applies: false, types: [] },
      CacheControlConfig: { applies: true },
      CompressConfig: {
        applies: true,
        supportedEncodings: [ 'br', 'gzip', 'identity', 'deflate' ]
      },
      CookieConfig: { applies: true, httponly: true, sameSite: 'lax', path: '/' },
      CorsConfig: { applies: true },
      DecompressConfig: {
        applies: true,
        supportedEncodings: [ 'br', 'gzip', 'deflate', 'identity' ]
      },
      EtagConfig: { applies: true, minimumSize: '10kb' },
      TrustProxyConfig: { applies: true, ips: [] },
      WebBodyConfig: {
        applies: true,
        limit: '1mb',
        parsingTypes: {
          text: 'text',
          'application/json': 'json',
          'application/x-www-form-urlencoded': 'form'
        }
      },
      WebConfig: { defaultMessage: true },
      WebHttpConfig: {
        httpVersion: '1.1',
        port: 3000,
        bindAddress: '0.0.0.0',
        tls: false
      },
      WebLogConfig: { applies: true, showStackTrace: true }
    }
  }
}
Listening on port { port: 3000 }

Configuration

Code: Standard Web Http Config

export class WebHttpConfig {
  /**
   * What version of HTTP to use
   * Version 2 requires SSL for direct browser access
   */
  @EnvVar('WEB_HTTP_VERSION')
  httpVersion: '1.1' | '2' = '1.1';

  /**
   * The port to run on
   */
  @EnvVar('WEB_HTTP_PORT')
  port: number = 3000;

  /**
   * The bind address, defaults to 0.0.0.0
   */
  bindAddress: string = '';

  /**
   * Is TLS active
   */
  @EnvVar('WEB_HTTP_TLS')
  tls?: boolean;

  /**
   * TLS Keys
   */
  @Secret()
  tlsKeys?: WebSecureKeyPair;

  @Ignore()
  fetchUrl: string;

  @PostConstruct()
  async finalizeConfig(): Promise<void> {
    this.tls ??= this.httpVersion === '2' || !!this.tlsKeys;
    this.port = this.port < 0 ? await NetUtil.getFreePort() : this.port;
    this.bindAddress ||= NetUtil.getLocalAddress();

    if (!this.tls) {
      // Clear out keys if tls is not set
      this.tlsKeys = undefined;
    } else if (!this.tlsKeys) {
      if (Runtime.production) {
        throw new RuntimeError('Default tls keys are only valid for development use, please specify a config value at web.tls.keys');
      }
      this.tlsKeys = await WebTlsUtil.generateKeyPair();
    } else {
      if (this.tlsKeys.key.length < 100) {
        // We have files or resources
        this.tlsKeys.key = await RuntimeResources.readUTF8(this.tlsKeys.key);
        this.tlsKeys.cert = await RuntimeResources.readUTF8(this.tlsKeys.cert);
      }
    }

    this.fetchUrl = `${this.tls ? 'https' : 'http'}://${this.bindAddress}:${this.port}`;
  }
}

Creating a Custom CLI Entry Point

To customize a Web server, you may need to construct an entry point using the @CliCommand decorator. This could look like:

Code: Application entry point for Web Applications

import { CliCommand } from '@travetto/cli';
import { DependencyRegistryIndex } from '@travetto/di';
import { Registry } from '@travetto/registry';
import { Env, toConcrete } from '@travetto/runtime';
import { WebHttpConfig, type WebHttpServer } from '@travetto/web-http';

import './config-override.ts';

@CliCommand({ runTarget: true })
export class SampleApp {
  preMain(): void {
    Env.NODE_ENV.set('production');
  }

  async main() {
    console.log('CUSTOM STARTUP');
    await Registry.init();
    const config = await DependencyRegistryIndex.getInstance(WebHttpConfig);
    config.tls = true;

    // Configure server before running
    const instance = await DependencyRegistryIndex.getInstance(toConcrete<WebHttpServer>());
    const { complete } = await instance.serve();
    return complete;
  }
}

And using the pattern established in the Command Line Interface module, you would run your program using npx trv web:custom.

Terminal: Custom application

$ trv web:custom

CUSTOM STARTUP
Initialized {
  manifest: {
    main: {
      name: '@travetto-doc/web-http',
      folder: './doc-exec'
    },
    workspace: {
      name: '@travetto-doc/web-http',
      path: './doc-exec',
      mono: false,
      manager: 'npm'
    }
  },
  runtime: {
    production: false,
    role: 'std',
    debug: false,
    resourcePaths: [
      './doc-exec/resources'
    ],
    profiles: []
  },
  config: {
    sources: [
      { priority: 10, source: 'direct' },
      { priority: 999, source: 'memory://override' }
    ],
    active: {
      AcceptConfig: { applies: false, types: [] },
      CacheControlConfig: { applies: true },
      CompressConfig: {
        applies: true,
        supportedEncodings: [ 'br', 'gzip', 'identity', 'deflate' ]
      },
      CookieConfig: { applies: true, httponly: true, sameSite: 'lax', path: '/' },
      CorsConfig: { applies: true },
      DecompressConfig: {
        applies: true,
        supportedEncodings: [ 'br', 'gzip', 'deflate', 'identity' ]
      },
      EtagConfig: { applies: true, minimumSize: '10kb' },
      TrustProxyConfig: { applies: true, ips: [] },
      WebBodyConfig: {
        applies: true,
        limit: '1mb',
        parsingTypes: {
          text: 'text',
          'application/json': 'json',
          'application/x-www-form-urlencoded': 'form'
        }
      },
      WebConfig: { defaultMessage: true },
      WebHttpConfig: {
        httpVersion: '1.1',
        port: 3000,
        bindAddress: '0.0.0.0',
        tls: true
      },
      WebLogConfig: { applies: true, showStackTrace: true }
    }
  }
}
Listening on port { port: 3000 }

Node Web Http Server

Code: Implementation

export class NodeWebHttpServer implements WebHttpServer {
  @Inject()
  serverConfig: WebHttpConfig;

  @Inject()
  router: StandardWebRouter;

  @Inject()
  configService: ConfigurationService;

  async serve(): Promise<WebServerHandle> {
    const handle = await WebHttpUtil.startHttpServer({ ...this.serverConfig, dispatcher: this.router });
    console.log('Initialized', await this.configService.initBanner());
    console.log('Listening', { port: this.serverConfig.port });
    return handle;
  }
}

Current the NodeWebHttpServer is the only provided WebHttpServer implementation. It supports http/1.1, http/2, and tls, and is the same foundation as used by express, koa, and other popular frameworks.

Standard Utilities

The module also provides standard utilities for starting http servers programmatically:

Code: Web Http Utilities

export class WebHttpUtil {
  /**
   * Build a simple request handler
   * @param dispatcher
   */
  static buildHandler(dispatcher: WebDispatcher): (request: HttpRequest, response: HttpResponse) => Promise<void>;
  /**
   * Start an http server
   */
  static async startHttpServer(config: WebHttpServerConfig): Promise<WebServerHandle<HttpServer>>;
  /**
   * Create a WebRequest given an incoming http request
   */
  static toWebRequest(request: HttpRequest): WebRequest;
  /**
   * Send WebResponse to outbound http response
   */
  static async respondToServerResponse(webResponse: WebResponse, response: HttpResponse): Promise<void>;
}

Specifically, looking at buildHandler,

Code: Web Http Utilities

static buildHandler(dispatcher: WebDispatcher): (request: HttpRequest, response: HttpResponse) => Promise<void> {
    return async (request: HttpRequest, response: HttpResponse): Promise<void> => {
      const webRequest = this.toWebRequest(request);
      const webResponse = await dispatcher.dispatch({ request: webRequest });
      await this.respondToServerResponse(webResponse, response);
    };
  }

we can see the structure for integrating the server behavior with the Web API module dispatcher:

  • Converting the node primitive request to a WebRequest
  • Dispatching the request through the framework
  • Receiving the WebResponse and sending that back over the primitive response.

TLS Support

Additionally the framework supports TLS out of the box, by allowing you to specify your public and private keys for the cert. In dev mode, the framework will also automatically generate a self-signed cert if:

  • TLS support is configured
  • node-forge is installed
  • Not running in production
  • No keys provided

This is useful for local development where you implicitly trust the cert.

TLS support can be enabled by setting web.http.tls: true in your config. The key/cert can be specified as string directly in the config file/environment variables. The key/cert can also be specified as a path to be picked up by RuntimeResources.