@travetto/web-http
v8.0.3
Published
Web HTTP Server Support
Maintainers
Readme
Web HTTP Server Support
Web HTTP Server Support
Install: @travetto/web-http
npm install @travetto/web-http
# or
yarn add @travetto/web-httpThis 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 8000Running 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.
