CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-sirv-cli

A lightweight CLI program to serve static sites with HTTP/2, compression, SPA support, and extensive configuration options

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

sirv-cli

sirv-cli is a lightweight command-line interface tool for serving static websites and files with high performance and comprehensive configuration options. It provides a fast alternative to other static file servers like http-server, featuring built-in support for HTTP/2, CORS headers, compression (gzip/brotli), ETag caching, single-page application (SPA) routing with customizable fallbacks, SSL/TLS certificates for secure serving, and flexible hosting options including network access control.

Package Information

  • Package Name: sirv-cli
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install sirv-cli (or npm install -g sirv-cli for global use)
  • Node.js Requirement: >=18
  • License: MIT

Core Imports

sirv-cli is primarily used as a CLI tool, but also exports a programmatic interface:

const serve = require("sirv-cli");

For ESM:

import serve from "sirv-cli";

Basic Usage

Command Line Interface

Start a basic static file server:

# Serve current directory on default port (8080)
sirv

# Serve specific directory
sirv public

# Serve with custom port and CORS enabled
sirv build --cors --port 8888

# Development mode with extensive logging
sirv public --dev --host

Programmatic Usage

const serve = require("sirv-cli");

// Serve a directory with options
serve("./public", {
  port: 3000,
  host: "localhost",
  cors: true,
  dev: true
});

Capabilities

Command Line Interface

The main CLI command for running a static file server.

sirv [dir] [options]

Parameters:

  • dir (string, optional): Directory to serve (defaults to current directory)

Available Options:

-D, --dev          # Enable development mode with enhanced logging
-e, --etag         # Enable ETag header for caching
-d, --dotfiles     # Enable serving dotfile assets (hidden files)
-c, --cors         # Enable CORS headers to allow any origin requestor
-G, --gzip         # Send precompiled "*.gz" files when gzip is supported (default: true)
-B, --brotli       # Send precompiled "*.br" files when brotli is supported (default: true)
-m, --maxage       # Enable Cache-Control header & define max-age value (seconds)
-i, --immutable    # Enable immutable directive for Cache-Control header
-k, --http2        # Enable HTTP/2 protocol (requires Node.js 8.4.0+)
-C, --cert         # Path to certificate file for HTTP/2 server
-K, --key          # Path to certificate key for HTTP/2 server
-P, --pass         # Passphrase to decrypt certificate key
-s, --single       # Serve as single-page application with index.html fallback
-I, --ignores      # URL pattern(s) to ignore for SPA index.html assumptions
-q, --quiet        # Disable logging to terminal
-H, --host         # Hostname to bind (default: localhost via CLI, falls back to 0.0.0.0)
-p, --port         # Port to bind (default: 8080)
-v, --version      # Display version information
-h, --help         # Display help message

Example Commands:

# Basic static serving
sirv public

# Production setup with compression and HTTP/2
sirv build --http2 --key server.key --cert server.crt --gzip --brotli

# SPA development with live reloading
sirv dist --single --dev --host --cors

# Custom port with cache headers
sirv public --port 3000 --etag --maxage 3600 --immutable

# Quiet mode for production
sirv build --quiet --maxage 31536000

Programmatic Server Function

Creates and starts an HTTP/HTTP2 server for static file serving.

/**
 * Create and start a static file server
 * @param {string} dir - Directory to serve (resolved to absolute path)
 * @param {ServerOptions} opts - Configuration options
 * @returns {void} - Starts server, does not return a value
 */
function serve(dir, opts);

interface ServerOptions {
  /** Port number to bind (overridden by PORT environment variable) */
  port?: number;
  /** Hostname to bind (overridden by HOST environment variable) */
  host?: string;
  /** Enable CORS headers */
  cors?: boolean;
  /** Enable HTTP/2 protocol */
  http2?: boolean;
  /** Path to SSL certificate key file */
  key?: string;
  /** Path to SSL certificate file */
  cert?: string;
  /** Path to CA certificate file */
  cacert?: string;
  /** Passphrase for SSL key decryption */
  pass?: string;
  /** Enable request logging (default: true) */
  logs?: boolean;
  /** Suppress output messages */
  quiet?: boolean;
  /** Clear console on startup (default: true) */
  clear?: boolean;
  /** Enable SSL/HTTPS without HTTP/2 */
  ssl?: boolean;
  /** Max-age value for Cache-Control header */
  m?: number;
}

Usage Examples:

const serve = require("sirv-cli");

// Basic server
serve("./public", {
  port: 3000,
  host: "localhost"
});

// Production server with HTTP/2 and caching
serve("./build", {
  http2: true,
  key: "./certs/server.key",
  cert: "./certs/server.crt",
  port: 443,
  host: "0.0.0.0",
  m: 31536000, // 1 year cache
  quiet: true
});

// Development server with CORS
serve("./src", {
  cors: true,
  port: 8080,
  logs: true
});

Environment Variables

Environment variables that override CLI flags and programmatic options.

HOST    # Overrides --host flag and opts.host
PORT    # Overrides --port flag and opts.port

Usage:

# Set via environment variables
HOST=0.0.0.0 PORT=3000 sirv public

# Environment variables take precedence over flags
PORT=8080 sirv --port 9000 public  # Will use port 8080

Single Page Application (SPA) Support

Enables serving Single Page Applications with proper routing fallbacks.

CLI Usage:

# Enable SPA mode with default index.html fallback
sirv public --single

# Custom fallback file
sirv public --single shell.html

# Ignore specific URL patterns from SPA fallback
sirv public --single --ignores "^/api" --ignores "^/assets"

Behavior:

  • Unknown paths (e.g., /foo/bar) serve the fallback file (default: index.html)
  • Asset requests (URLs ending with extensions) return 404 instead of fallback
  • Ignored patterns bypass SPA behavior entirely

Default Ignore Patterns: By default, sirv ignores these patterns from SPA fallback:

  • Any URL ending with an extension: /[A-Za-z\s\d~$._-]+\.\w+$/
  • Dotfiles (when --dotfiles disabled): /\.\w/
  • Well-known paths (always allowed): /.well-known/
  • Custom patterns can be added with --ignores flag

HTTP/2 and SSL Support

Enable secure serving with HTTP/2 protocol support.

Requirements:

  • Node.js version 8.4.0 or later
  • Valid SSL certificate and key files
  • No unencrypted HTTP/2 support (browsers require SSL)

CLI Usage:

# HTTP/2 with SSL certificates
sirv public --http2 --key server.key --cert server.crt

# With passphrase-protected key
sirv public --http2 --key encrypted.key --cert server.crt --pass mypassword

# With CA certificate
sirv public --http2 --key server.key --cert server.crt --cacert ca.crt

Certificate Generation:

# Self-signed certificate for development
openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \
  -keyout localhost-key.pem -out localhost-cert.pem

# Using mkcert for trusted local certificates
mkcert -install
mkcert -key-file localhost-key.pem -cert-file localhost-cert.pem localhost 127.0.0.1

Compression Support

Built-in support for serving pre-compressed files.

File Lookup Order:

For a request to /style.css with Accept-Encoding: br, gzip, sirv will look for files in this order:

  1. /style.css.br (if brotli enabled and supported)
  2. /style.css.gz (if gzip enabled and supported)
  3. /style.css (original file)
  4. /style.css.html and /style.css/index.html (extension fallbacks)
  5. /style.css.htm and /style.css/index.htm (extension fallbacks)

Extension Fallback Behavior: By default, sirv tries ['html', 'htm'] extensions for any request. This means:

  • /about → tries /about, /about.html, /about/index.html, /about.htm, /about/index.htm
  • Can be customized via extensions option in programmatic usage

CLI Usage:

# Enable both compression types (default behavior)
sirv public --gzip --brotli

# Disable compression
sirv public --no-gzip --no-brotli

# Only gzip compression
sirv public --gzip --no-brotli

Caching and Performance

Control caching behavior with ETag and Cache-Control headers.

Production vs Development Mode:

Production Mode (default):

  • Pre-scans directory and caches file metadata on startup
  • Serves files from memory cache for maximum performance
  • Uses Cache-Control headers based on maxAge and immutable settings
  • File system is only accessed during server initialization

Development Mode (--dev):

  • Reads file system on every request for live updates
  • Ignores maxAge and immutable settings
  • Sets Cache-Control: no-cache or Cache-Control: no-store
  • Slower but allows real-time file changes

CLI Usage:

# Enable ETag headers
sirv public --etag

# Set cache max-age (in seconds)
sirv public --maxage 3600

# Enable immutable cache directive
sirv public --maxage 31536000 --immutable

# Development mode (disables caching optimizations)
sirv public --dev

Cache-Control Header Examples:

  • --maxage 3600: Cache-Control: public, max-age=3600
  • --maxage 3600 --immutable: Cache-Control: public, max-age=3600, immutable

Network Access Control

Control server accessibility and security.

Local-only (default):

sirv public  # Only accessible from localhost

Network accessible:

sirv public --host  # Equivalent to --host 0.0.0.0
sirv public --host 192.168.1.100  # Bind to specific IP

Security Note: Use --host only when you need network access, as it exposes the server publicly.

Logging and Output Control

Control server logging and console output.

CLI Usage:

# Quiet mode (no output)
sirv public --quiet

# Disable request logging only
sirv public --logs false

# Development mode with enhanced logging
sirv public --dev

Log Format:

[14:32:15] 200 ─ 1.23ms ─ /index.html
[14:32:15] 404 ─ 0.45ms ─ /missing.js

Error Handling

sirv-cli includes built-in error handling for common scenarios:

HTTP/2 Requirements:

  • Validates Node.js version (8.4.0+)
  • Requires both --key and --cert for HTTP/2
  • Validates certificate file existence

Port Management:

  • Automatically finds alternative port if specified port is taken
  • Shows port change notification in output

SSL Certificate Handling:

  • Reads certificate files from file system
  • Supports passphrase-protected keys
  • Handles CA certificate chains

Common Error Messages:

# HTTP/2 version error
ERROR: HTTP/2 requires Node v8.4.0 or greater

# Missing SSL certificates
ERROR: HTTP/2 requires "key" and "cert" values

# File system errors for certificates handled internally

Integration Patterns

Development Workflow

# Development with live reloading indicators
sirv src --dev --host --cors --single

# API proxy development (combine with proxy tools)
sirv build --port 3000 --cors  # Frontend
# Proxy /api/* to localhost:8000 (backend)

Production Deployment

# Production-optimized serving
sirv build \
  --http2 \
  --key /path/to/server.key \
  --cert /path/to/server.crt \
  --gzip \
  --brotli \
  --maxage 31536000 \
  --immutable \
  --quiet

CI/CD Integration

# Preview builds in CI
sirv dist --port 8080 --quiet &
SERVER_PID=$!
# Run tests against localhost:8080
kill $SERVER_PID

Types

// Environment variables interface
interface EnvironmentOverrides {
  HOST?: string;  // Hostname override
  PORT?: string;  // Port number override (as string)
}

// Server configuration options
interface ServerOptions {
  port?: number;      // Port to bind
  host?: string;      // Hostname to bind  
  cors?: boolean;     // Enable CORS headers
  http2?: boolean;    // Enable HTTP/2 protocol
  key?: string;       // SSL key file path
  cert?: string;      // SSL certificate file path
  cacert?: string;    // CA certificate file path
  pass?: string;      // SSL key passphrase
  logs?: boolean;     // Enable request logging
  quiet?: boolean;    // Suppress output messages
  clear?: boolean;    // Clear console on startup
  ssl?: boolean;      // Enable SSL
  m?: number;         // Cache max-age value
}

// CLI option mapping (internal)
interface CLIOptions extends ServerOptions {
  dev?: boolean;      // Development mode
  etag?: boolean;     // Enable ETag headers
  dotfiles?: boolean; // Serve dotfiles
  gzip?: boolean;     // Enable gzip compression
  brotli?: boolean;   // Enable brotli compression
  maxage?: number;    // Cache-Control max-age
  immutable?: boolean;// Cache-Control immutable
  single?: boolean;   // SPA mode
  ignores?: string;   // SPA ignore patterns
}
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/sirv-cli@3.0.x
Publish Source
CLI
Badge
tessl/npm-sirv-cli badge