or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

authentication.mdcaching.mdextensions.mdindex.mdplugin-system.mdrequest-processing.mdresponse-management.mdrouting.mdserver-management.mdvalidation.md
tile.json

server-management.mddocs/

Server Management

Core server creation, configuration, and lifecycle management functionality for setting up and controlling HTTP servers in @hapi/hapi.

Capabilities

Server Factory Function

Creates a new hapi server instance with optional configuration.

/**
 * Creates a new hapi server instance
 * @param options - Optional server configuration object
 * @returns Server instance
 */
function server(options?: ServerOptions): Server;

interface ServerOptions {
    /** IP address or hostname to bind the server to */
    address?: string;
    /** Application-specific configuration object */
    app?: object;
    /** Whether to automatically start the listener */
    autoListen?: boolean;
    /** Cache configuration */
    cache?: CacheOptions | CacheOptions[];
    /** Response compression settings or false to disable */
    compression?: CompressionOptions | false;
    /** Debug logging configuration or false to disable */
    debug?: DebugOptions | false;
    /** Hostname or IP address for server.info */
    host?: string;
    /** Additional server information settings */
    info?: { remote?: boolean };
    /** Custom HTTP/HTTPS listener object */
    listener?: object;
    /** Server load monitoring settings */
    load?: LoadOptions;
    /** MIME type configuration */
    mime?: MimeOptions;
    /** Server operations settings */
    operations?: OperationsOptions;
    /** Plugin-specific configuration */
    plugins?: object;
    /** Port number or string to listen on */
    port?: number | string;
    /** Query string parsing options */
    query?: QueryOptions;
    /** Router configuration */
    router?: RouterOptions;
    /** Default route options */
    routes?: RouteOptions;
    /** Cookie state configuration */
    state?: StateOptions;
    /** TLS/SSL configuration */
    tls?: object | boolean;
    /** Full URI override */
    uri?: string;
}

Usage Examples:

const Hapi = require('@hapi/hapi');

// Basic server
const server = Hapi.server({
    port: 3000,
    host: 'localhost'
});

// Advanced configuration
const server = Hapi.server({
    port: process.env.PORT || 8080,
    host: '0.0.0.0',
    compression: { minBytes: 1024 },
    cache: {
        provider: {
            constructor: require('@hapi/catbox-redis'),
            options: { url: 'redis://localhost:6379' }
        }
    },
    routes: {
        cors: true,
        validate: {
            options: { abortEarly: false }
        }
    }
});

Server Lifecycle Management

Methods for controlling the server lifecycle including initialization, starting, and stopping.

/**
 * Initialize the server without starting the listener
 * @returns Promise that resolves when initialization is complete
 */
initialize(): Promise<void>;

/**
 * Start the server and begin accepting connections
 * @returns Promise that resolves when server is started
 */
start(): Promise<void>;

/**
 * Stop the server and close all connections
 * @param options - Stop options
 * @returns Promise that resolves when server is stopped
 */
stop(options?: StopOptions): Promise<void>;

interface StopOptions {
    /** Timeout in milliseconds to force close connections */
    timeout?: number;
}

Usage Examples:

const init = async () => {
    const server = Hapi.server({ port: 3000 });
    
    // Add routes and plugins
    server.route({
        method: 'GET',
        path: '/',
        handler: () => 'Hello World!'
    });
    
    // Initialize server
    await server.initialize();
    console.log('Server initialized');
    
    // Start server
    await server.start();
    console.log('Server started at:', server.info.uri);
    
    // Graceful shutdown
    process.on('SIGINT', async () => {
        await server.stop({ timeout: 10000 });
        console.log('Server stopped');
        process.exit(0);
    });
};

Server Information

Access to server runtime information and configuration.

interface ServerInfo {
    /** Unique server identifier */
    id: string;
    /** Server creation timestamp */
    created: number;
    /** Server start timestamp */
    started: number;
    /** Server port number */
    port: number;
    /** Server hostname */
    host: string;
    /** Server address */
    address: string;
    /** Server protocol (http or https) */
    protocol: string;
    /** Full server URI */
    uri: string;
}

Server Context Binding

Set the execution context for route handlers and extensions.

/**
 * Set the context object for binding in handlers
 * @param context - Context object to bind
 */
bind(context: object): void;

Usage Examples:

const server = Hapi.server({ port: 3000 });

// Bind context
server.bind({
    database: db,
    logger: logger,
    config: config
});

server.route({
    method: 'GET',
    path: '/users',
    handler: function(request, h) {
        // Access bound context via 'this'
        const users = this.database.users.findAll();
        this.logger.info('Retrieved users');
        return users;
    }
});

Server Control

Control another server instance from within a plugin or handler.

/**
 * Control another server instance
 * @param server - Server instance to control
 */
control(server: Server): void;

Content Encoding and Decoding

Register custom content encoders and decoders for request/response processing.

/**
 * Register a content encoder
 * @param encoding - Encoding name (e.g., 'gzip', 'deflate')
 * @param encoder - Encoding function
 */
encoder(encoding: string, encoder: Function): void;

/**
 * Register a content decoder
 * @param encoding - Encoding name (e.g., 'gzip', 'deflate')
 * @param decoder - Decoding function
 */
decoder(encoding: string, decoder: Function): void;

Usage Examples:

const zlib = require('zlib');

// Register custom gzip encoder
server.encoder('gzip', (content, encoding, callback) => {
    zlib.gzip(content, callback);
});

// Register custom gzip decoder
server.decoder('gzip', (content, encoding, callback) => {
    zlib.gunzip(content, callback);
});

Logging

Server-level event logging functionality.

/**
 * Log server event with tags and optional data
 * @param tags - String or array of tags
 * @param data - Optional event data
 */
log(tags: string | string[], data?: any): void;

Usage Examples:

const server = Hapi.server({ port: 3000 });

// Log events
server.log(['info', 'startup'], 'Server initialization started');
server.log('error', new Error('Configuration error'));
server.log(['debug', 'database'], { query: 'SELECT * FROM users' });

// Listen to log events
server.events.on('log', (event, tags) => {
    if (tags.error) {
        console.error('Server error:', event.data);
    }
});

Types

interface CompressionOptions {
    /** Minimum response size in bytes for compression */
    minBytes?: number;
}

interface DebugOptions {
    /** Server log tags to display in console */
    log?: string[] | false;
    /** Request log tags to display in console */
    request?: string[] | false | '*';
}

interface LoadOptions {
    /** Sampling interval in milliseconds */
    sampleInterval?: number;
    /** Maximum heap usage in bytes */
    maxHeapUsedBytes?: number;
    /** Maximum RSS in bytes */
    maxRssBytes?: number;
    /** Maximum event loop delay in milliseconds */
    maxEventLoopDelay?: number;
}

interface QueryOptions {
    /** Maximum number of query parameters */
    maxKeys?: number;
}

interface RouterOptions {
    /** Whether routes are case sensitive */
    isCaseSensitive?: boolean;
    /** Whether to strip trailing slashes */
    stripTrailingSlash?: boolean;
}

interface MimeOptions {
    /** Override default MIME type mappings */
    override?: { [extension: string]: { type: string; charset?: string } };
}

interface OperationsOptions {
    /** Maximum number of concurrent operations */
    max?: number;
    /** Operation cleanup interval in milliseconds */
    cleanupInterval?: number;
}