sirv

repository·main·Indexed 22 days ago

https://github.com/lukeed/sirv

An optimized and lightweight middleware for serving static assets in Node.js, designed as a high-performance alternative to serve-static. It includes a core module for use in frameworks like Express or Polka, and sirv-cli, a standalone command-line tool for serving static sites. Key features include production caching, HTTP/2 support, Single Page Application (SPA) mode, and precompiled Gzip and Brotli compression.

Tokens
5.6K
Snippets
19
Records
34
Agent score
77%

What's inside sirv

  1. Overview of sirv and sirv-cli

    main

    sirv is a high-performance toolset for serving static files, split into two main components:

    • sirv: The core Node.js module. It returns a middleware function designed for use in Express-like frameworks or Polka.
    • sirv-cli: A standalone Command Line Interface (CLI) application used for instant previews of static websites.
  2. Configure network access and host binding

    main

    By default, sirv-cli only exposes the server to localhost. To make the server accessible to other devices on your network (e.g., mobile devices or coworkers), use the --host flag.

    • Using --host without a value is equivalent to --host 0.0.0.0, making it discoverable publicly.
    • You can provide a specific hostname or IP address to --host to customize binding.
  3. Configure Single Page Application (SPA) mode

    main

    Enable SPA mode using the --single flag. This causes the server to serve index.html (or a custom fallback file) when a requested path does not resolve to a file.

    • Custom Fallback: Use --single <filename> to specify a file other than index.html (e.g., --single shell.html).
    • Asset Requests: URLs ending in an extension (e.g., /image.png) bypass SPA mode and return a 404 if not found.
    • Excluding Paths: Use the --ignores flag with URL patterns to prevent certain paths from triggering the SPA fallback.
    # Don't include "/blog*" or "/portfolio*" pages into SPA
    $ sirv public --single --ignores "^/blog" --ignores "^/portfolio"
  4. Compare sirv performance via benchmarks

    main

    The project provides benchmark data comparing sirv against other popular static file servers.

    Programmatic Usage

    When used as a middleware within a Node.js server, sirv is compared against serve-static. Performance varies based on whether dev mode is enabled:

    • sirv (dev: false): Optimized for production with high request/sec and low latency.
    • sirv (dev: true): Optimized for development, which typically results in lower performance due to additional development-specific features.

    CLI Usage

    When used as a standalone application, sirv-cli is compared against http-server. Performance can be tuned using flags like --dev (disables caching) and --no-logs (disables logging).

  5. Enable HTTP/2 with SSL

    main

    To use HTTP/2, you must provide a valid certificate and key using the --cert and --key flags, as browsers require encryption for HTTP/2. This requires Node.js v8.4.0 or later.

    Quick setup with OpenSSL:

    $ openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \
      -keyout localhost-key.pem -out localhost-cert.pem
    
    # Run the server
    $ sirv --http2 --key localhost-key.pem --cert localhost-cert.pem

    Using mkcert for locally-trusted certificates:

    $ mkcert -install
    $ mkcert -key-file localhost-key.pem -cert-file localhost-cert.pem localhost 127.0.0.1
    
    # Run the server
    $ sirv --http2 --key localhost-key.pem --cert localhost-cert.pem
    $ sirv --http2 --key localhost-key.pem --cert localhost-cert.pem
  6. Use sirv-cli to serve a directory

    main

    Run the sirv command followed by the directory you wish to serve and any desired options.

    Important: The HOST and PORT environment variables will override the --host and --port flags, respectively.

    $ sirv [dir] [options]
    
    # Examples
    $ sirv build --cors --port 8888
    $ sirv public --quiet --etag --maxage 31536000 --immutable
    $ sirv public --http2 --key priv.pem --cert cert.pem
    $ sirv public -qeim 31536000
    $ sirv --port 8888 --etag
    $ sirv --host --dev
  7. Best practices for Production

    main

    When using sirv-cli in a production environment, follow these recommendations for security and performance:

    1. Disable Dev Mode: Ensure --dev is not used.
    2. Enable HTTP/2: Use --http2 with valid SSL certificates (--key and --cert).
    3. Compression: Precompile .br (Brotli) and .gz (Gzip) file variants and enable them using the --brotli and --gzip flags.
    4. Minimize I/O: Use the --quiet flag to disable terminal logging.

    Note: While sirv-cli is production-ready, using a CDN or specialized web servers like NGINX or h2o is recommended for high-performance needs.

  8. Enable Single Page Application (SPA) mode

    main

    To support client-side routing in an SPA, use the single option. When a requested path does not match a physical file, sirv will serve the fallback file instead of a 404.

    If single is a string, it is used as the fallback path. If it is a boolean true, it defaults to /.

    import sirv from 'sirv';
    
    // Fallback to index.html for all non-file requests
    const middleware = sirv('dist', { single: 'index.html' });
  9. Use the sirv-cli to serve static files

    main

    The sirv-cli package provides a command-line interface for the sirv static file server. It allows you to serve a directory of files with various options for CORS, HTTP/2, SSL, and logging. When started, it provides local and network access URLs and can automatically find an available port if the requested one is occupied.

    Key Features

    • Automatic Port Discovery: If the specified port is taken, it will use an alternative port and notify you.
    • HTTP/2 Support: Enables HTTP/2 when provided with key and cert files.
    • CORS Support: Automatically sets Access-Control-Allow-Origin: * and standard headers when the --cors flag is used.
    • Logging: Provides timestamped, color-coded request logs (status code, duration, and URI) by default.
    # Example usage (assuming sirv-cli is installed globally or via npx)
    npx sirv ./public --port 3000 --cors
  10. Enable HTTP/2 in sirv-cli

    main

    To use HTTP/2, you must use the --http2 flag and provide valid SSL certificate files using --key and --cert. The CLI will automatically read these files from the paths provided. Note that HTTP/2 requires Node.js v8.4.0 or greater.

    Requirements:

    • --http2 flag
    • --key <path>
    • --cert <path>

    If --http2 is enabled, the server will also allow HTTP/1 connections for compatibility.

    npx sirv ./public --http2 --key ./path/to/key.pem --cert ./path/to/cert.pem