serve

repository·main·Indexed 27 days ago

https://github.com/vercel/serve

A tool for serving static sites, single page applications (SPAs), or individual static files. It provides a directory listing interface and can be used as a standalone CLI or integrated as middleware in Node.js HTTP servers via the serve-handler package. Version 14.2.6 requires Node v14 or higher. Key features include SPA mode with the --single flag, custom configuration via serve.json, CORS support, and SSL/TLS configuration for HTTPS.

Tokens
2K
Snippets
2
Records
14
Agent score
94%

What's inside serve

  1. Install and run serve

    main

    You can use serve without installing it by using npx, or you can install it globally to use the serve command directly in your terminal.

    Note: serve v14+ requires Node v14 or higher. If you are on an older Node version, use serve v13.

  2. Use the `serve` CLI

    main

    The serve CLI is used for static file serving and directory listing. By default, it listens on 0.0.0.0:3000 and serves the current working directory.

    Basic Usage Patterns:

    • Serve the current directory: serve
    • Serve a specific folder: serve folder_name
    • Show help: serve --help
    • Check version: serve --version
  3. Configure SPA rewrites with `--single`

    main
    When using the --single flag, serve automatically adds a rewrite rule that directs all requests (**) to /index.html. This rule is inserted at the beginning of the rewrites array in your configuration to ensure it takes priority over any existing rewrite rules.
  4. Use serve-handler as middleware

    main

    The core logic of serve is provided by serve-handler, which can be integrated into existing HTTP servers (like Node's http module or micro) as middleware.

    const handler = require('serve-handler');
    const http = require('http');
    
    const server = http.createServer((request, response) => {
      // You pass two more arguments for config and middleware
      // More details here: https://github.com/vercel/serve-handler#options
      return handler(request, response);
    });
    
    server.listen(3000, () => {
      console.log('Running at http://localhost:3000');
    });
  5. Start the static file server with startServer()

    main

    The startServer function initializes and runs an HTTP or HTTPS server to serve static files. It handles request logging, CORS headers, compression, and SSL configuration based on the provided arguments.

    Parameters

    • endpoint: A ParsedEndpoint object defining where to listen (host and port).
    • config: A Partial<Configuration> object containing settings for the serve-handler middleware.
    • args: A Partial<Options> object containing CLI-style flags that control server behavior (e.g., --cors, --no-compression, --ssl-cert).
    • previous (optional): A Port value used if the server needs to fallback to a different port.

    Behavior

    • Port Conflict: If the requested port is already in use, the function will automatically attempt to start the server on a random port (port 0) and return the original port in the previous field of the result.
    • SSL/TLS: Supports both PEM (using ssl-cert and ssl-key) and PFX/P12 formats (using ssl-cert with a .pfx or .p12 extension).
    • CORS: If the --cors flag is present in args, it enables wide CORS support by setting Access-Control-Allow-Origin to * and enabling credentials and private network access.
    • Compression: Uses the compression middleware unless the --no-compression flag is present in args.
    • Logging: Logs HTTP requests to the console unless the --no-request-logging flag is present in args.

    Returns

    Returns a Promise<ServerAddress> containing the local and network URLs of the running server.

  6. Environment variables for `serve`

    main

    The following environment variables affect the serve CLI behavior:

    • PORT: Sets the default port if no --listen argument is provided. Defaults to 3000 if not set.
    • NODE_ENV: If set to production, the CLI will suppress the interactive 'fancy box' output and instead print a single line of text for the server address to stdout.
  7. Specify listen endpoints with `--listen`

    main

    The --listen (or -l) option allows you to specify one or more interfaces, ports, UNIX domain sockets, or Windows named pipes. Specifying multiple --listen arguments allows the server to listen in multiple places simultaneously.

    Supported Endpoint Formats:

    • Port number only (defaults to localhost): serve -l 1234
    • TCP (host:port): serve -l tcp://hostname:1234
    • UNIX domain socket: serve -l unix:/path/to/socket.sock
    • Windows named pipe: serve -l pipe:\\.\pipe\PipeName
  8. Configure `serve` CLI flags

    main

    The following CLI flags are available to control the behavior of the serve command:

    • --help: Displays the help text and exits.
    • --version: Displays the current version of the package and exits.
    • --listen <port>: Specifies the port(s) to listen on. (Note: The implementation expects a specific format, typically used via the internal parser).
    • --single: Enables Single Page Application (SPA) mode by rewriting all requests to /index.html as the highest priority rule.
    • --no-clipboard: Disables the automatic copying of the local server address to the clipboard.
    • --debug: Enables debug logging for errors (e.g., when checking for updates).
  9. Control server behavior via CLI arguments

    main

    The startServer function accepts an args object (of type Partial<Options>) that mimics CLI flags to toggle specific features:

    FlagDescription
    --corsEnables CORS by setting Access-Control-Allow-Origin: *, Access-Control-Allow-Headers: *, Access-Control-Allow-Credentials: true, and Access-Control-Allow-Private-Network: true.
    --no-compressionDisables the compression middleware.
    --no-request-loggingDisables HTTP request logging in the console.
    --ssl-certPath to the SSL certificate file.
    --ssl-keyPath to the SSL private key file (for PEM).
    --ssl-passPath to the file containing the SSL passphrase.
  10. Configure `serve` CLI options

    main

    Use the following flags to customize the behavior of the serve command:

    FlagAliasDescription
    --help-hShows this help message
    --version-vDisplays the current version
    --listen-lSpecify one or more URI endpoints to listen on
    --single-sRewrite all not-found requests to index.html (SPA mode)
    --debug-dShow debugging information
    --config-cSpecify custom path to serve.json
    --no-request-logging-LDo not log request information to the console
    --cors-CEnable CORS (sets Access-Control-Allow-Origin to *)
    --no-clipboard-nDo not copy the local address to the clipboard
    --no-compression-uDo not compress files
    --no-etagSend Last-Modified header instead of ETag
    --symlinks-SResolve symlinks instead of showing 404 errors
    --no-port-switchingDo not open a port other than the one specified when it's taken

    HTTPS/SSL Options:

    • --ssl-cert | Path to SSL/TLS certificate (PEM or PKCS12/PFX) |
    • --ssl-key | Path to the SSL/TLS private key (PEM only) |
    • --ssl-pass | Path to the SSL/TLS certificate's passphrase |