http-server: A Simple Static HTTP Server

14.1.1 · active · verified Sun Apr 19

http-server is a robust, zero-configuration command-line HTTP server designed for serving static files efficiently. Currently stable at version `14.1.1`, it has a reasonably active release cadence, addressing security vulnerabilities, adding new features, and dropping older Node.js support. Its key differentiators include ease of use via a simple CLI, support for HTTPS, automatic gzip/brotli compression, CORS headers, basic authentication, and proxying capabilities. It is suitable for local development, testing, and production environments, providing a quick way to serve content without complex setup. The project recently underwent a significant refactor by internalizing the `ecstatic` library's functionality, reducing external dependencies.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically start an http-server instance, configure it with common options like CORS, port, and root directory, and serve static content. It also includes basic custom logging.

const http = require('http-server');
const path = require('path');
const fs = require('fs');

// Create a temporary public directory and some static files
const publicDir = path.join(__dirname, 'public-server-root');
if (!fs.existsSync(publicDir)) {
  fs.mkdirSync(publicDir);
}
fs.writeFileSync(path.join(publicDir, 'index.html'), '<h1>Hello from http-server programmatically!</h1>');
fs.writeFileSync(path.join(publicDir, 'data.json'), '{"message": "API data from static file"}');

const options = {
  root: publicDir, // Directory to serve files from
  port: 8080,
  host: '0.0.0.0',
  cache: -1, // Disable caching for development
  cors: true, // Enable CORS
  showDir: true, // Show directory listings
  autoIndex: true, // Display autoIndex
  ssl: false, // No SSL for this example
  logFn: (req, res, error) => {
    // Custom logging for each request
    console.log(`[${new Date().toISOString()}] ${req.method} ${req.url} - ${res.statusCode}`);
  }
};

const serverInstance = http.createServer(options);

serverInstance.listen(options.port, options.host, () => {
  console.log(`http-server running on http://${options.host}:${options.port}`);
  console.log(`Serving files from: ${options.root}`);
  console.log('Access http://localhost:8080/index.html or http://localhost:8080/data.json');
});

// To stop the server gracefully, you would call serverInstance.close();

view raw JSON →