or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-sirv-cli

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

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/sirv-cli@3.0.x

To install, run

npx @tessl/cli install tessl/npm-sirv-cli@3.0.0

0

# sirv-cli

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: sirv-cli

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install sirv-cli` (or `npm install -g sirv-cli` for global use)

10

- **Node.js Requirement**: >=18

11

- **License**: MIT

12

13

## Core Imports

14

15

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

16

17

```javascript

18

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

19

```

20

21

For ESM:

22

23

```javascript

24

import serve from "sirv-cli";

25

```

26

27

## Basic Usage

28

29

### Command Line Interface

30

31

Start a basic static file server:

32

33

```bash

34

# Serve current directory on default port (8080)

35

sirv

36

37

# Serve specific directory

38

sirv public

39

40

# Serve with custom port and CORS enabled

41

sirv build --cors --port 8888

42

43

# Development mode with extensive logging

44

sirv public --dev --host

45

```

46

47

### Programmatic Usage

48

49

```javascript

50

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

51

52

// Serve a directory with options

53

serve("./public", {

54

port: 3000,

55

host: "localhost",

56

cors: true,

57

dev: true

58

});

59

```

60

61

## Capabilities

62

63

### Command Line Interface

64

65

The main CLI command for running a static file server.

66

67

```bash { .api }

68

sirv [dir] [options]

69

```

70

71

**Parameters:**

72

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

73

74

**Available Options:**

75

76

```bash { .api }

77

-D, --dev # Enable development mode with enhanced logging

78

-e, --etag # Enable ETag header for caching

79

-d, --dotfiles # Enable serving dotfile assets (hidden files)

80

-c, --cors # Enable CORS headers to allow any origin requestor

81

-G, --gzip # Send precompiled "*.gz" files when gzip is supported (default: true)

82

-B, --brotli # Send precompiled "*.br" files when brotli is supported (default: true)

83

-m, --maxage # Enable Cache-Control header & define max-age value (seconds)

84

-i, --immutable # Enable immutable directive for Cache-Control header

85

-k, --http2 # Enable HTTP/2 protocol (requires Node.js 8.4.0+)

86

-C, --cert # Path to certificate file for HTTP/2 server

87

-K, --key # Path to certificate key for HTTP/2 server

88

-P, --pass # Passphrase to decrypt certificate key

89

-s, --single # Serve as single-page application with index.html fallback

90

-I, --ignores # URL pattern(s) to ignore for SPA index.html assumptions

91

-q, --quiet # Disable logging to terminal

92

-H, --host # Hostname to bind (default: localhost via CLI, falls back to 0.0.0.0)

93

-p, --port # Port to bind (default: 8080)

94

-v, --version # Display version information

95

-h, --help # Display help message

96

```

97

98

**Example Commands:**

99

100

```bash

101

# Basic static serving

102

sirv public

103

104

# Production setup with compression and HTTP/2

105

sirv build --http2 --key server.key --cert server.crt --gzip --brotli

106

107

# SPA development with live reloading

108

sirv dist --single --dev --host --cors

109

110

# Custom port with cache headers

111

sirv public --port 3000 --etag --maxage 3600 --immutable

112

113

# Quiet mode for production

114

sirv build --quiet --maxage 31536000

115

```

116

117

### Programmatic Server Function

118

119

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

120

121

```javascript { .api }

122

/**

123

* Create and start a static file server

124

* @param {string} dir - Directory to serve (resolved to absolute path)

125

* @param {ServerOptions} opts - Configuration options

126

* @returns {void} - Starts server, does not return a value

127

*/

128

function serve(dir, opts);

129

130

interface ServerOptions {

131

/** Port number to bind (overridden by PORT environment variable) */

132

port?: number;

133

/** Hostname to bind (overridden by HOST environment variable) */

134

host?: string;

135

/** Enable CORS headers */

136

cors?: boolean;

137

/** Enable HTTP/2 protocol */

138

http2?: boolean;

139

/** Path to SSL certificate key file */

140

key?: string;

141

/** Path to SSL certificate file */

142

cert?: string;

143

/** Path to CA certificate file */

144

cacert?: string;

145

/** Passphrase for SSL key decryption */

146

pass?: string;

147

/** Enable request logging (default: true) */

148

logs?: boolean;

149

/** Suppress output messages */

150

quiet?: boolean;

151

/** Clear console on startup (default: true) */

152

clear?: boolean;

153

/** Enable SSL/HTTPS without HTTP/2 */

154

ssl?: boolean;

155

/** Max-age value for Cache-Control header */

156

m?: number;

157

}

158

```

159

160

**Usage Examples:**

161

162

```javascript

163

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

164

165

// Basic server

166

serve("./public", {

167

port: 3000,

168

host: "localhost"

169

});

170

171

// Production server with HTTP/2 and caching

172

serve("./build", {

173

http2: true,

174

key: "./certs/server.key",

175

cert: "./certs/server.crt",

176

port: 443,

177

host: "0.0.0.0",

178

m: 31536000, // 1 year cache

179

quiet: true

180

});

181

182

// Development server with CORS

183

serve("./src", {

184

cors: true,

185

port: 8080,

186

logs: true

187

});

188

```

189

190

### Environment Variables

191

192

Environment variables that override CLI flags and programmatic options.

193

194

```bash { .api }

195

HOST # Overrides --host flag and opts.host

196

PORT # Overrides --port flag and opts.port

197

```

198

199

**Usage:**

200

201

```bash

202

# Set via environment variables

203

HOST=0.0.0.0 PORT=3000 sirv public

204

205

# Environment variables take precedence over flags

206

PORT=8080 sirv --port 9000 public # Will use port 8080

207

```

208

209

### Single Page Application (SPA) Support

210

211

Enables serving Single Page Applications with proper routing fallbacks.

212

213

**CLI Usage:**

214

215

```bash

216

# Enable SPA mode with default index.html fallback

217

sirv public --single

218

219

# Custom fallback file

220

sirv public --single shell.html

221

222

# Ignore specific URL patterns from SPA fallback

223

sirv public --single --ignores "^/api" --ignores "^/assets"

224

```

225

226

**Behavior:**

227

- Unknown paths (e.g., `/foo/bar`) serve the fallback file (default: `index.html`)

228

- Asset requests (URLs ending with extensions) return 404 instead of fallback

229

- Ignored patterns bypass SPA behavior entirely

230

231

**Default Ignore Patterns:**

232

By default, sirv ignores these patterns from SPA fallback:

233

- Any URL ending with an extension: `/[A-Za-z\s\d~$._-]+\.\w+$/`

234

- Dotfiles (when `--dotfiles` disabled): `/\.\w/`

235

- Well-known paths (always allowed): `/.well-known/`

236

- Custom patterns can be added with `--ignores` flag

237

238

### HTTP/2 and SSL Support

239

240

Enable secure serving with HTTP/2 protocol support.

241

242

**Requirements:**

243

- Node.js version 8.4.0 or later

244

- Valid SSL certificate and key files

245

- No unencrypted HTTP/2 support (browsers require SSL)

246

247

**CLI Usage:**

248

249

```bash

250

# HTTP/2 with SSL certificates

251

sirv public --http2 --key server.key --cert server.crt

252

253

# With passphrase-protected key

254

sirv public --http2 --key encrypted.key --cert server.crt --pass mypassword

255

256

# With CA certificate

257

sirv public --http2 --key server.key --cert server.crt --cacert ca.crt

258

```

259

260

**Certificate Generation:**

261

262

```bash

263

# Self-signed certificate for development

264

openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \

265

-keyout localhost-key.pem -out localhost-cert.pem

266

267

# Using mkcert for trusted local certificates

268

mkcert -install

269

mkcert -key-file localhost-key.pem -cert-file localhost-cert.pem localhost 127.0.0.1

270

```

271

272

### Compression Support

273

274

Built-in support for serving pre-compressed files.

275

276

**File Lookup Order:**

277

278

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

279

280

1. `/style.css.br` (if brotli enabled and supported)

281

2. `/style.css.gz` (if gzip enabled and supported)

282

3. `/style.css` (original file)

283

4. `/style.css.html` and `/style.css/index.html` (extension fallbacks)

284

5. `/style.css.htm` and `/style.css/index.htm` (extension fallbacks)

285

286

**Extension Fallback Behavior:**

287

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

288

- `/about` → tries `/about`, `/about.html`, `/about/index.html`, `/about.htm`, `/about/index.htm`

289

- Can be customized via `extensions` option in programmatic usage

290

291

**CLI Usage:**

292

293

```bash

294

# Enable both compression types (default behavior)

295

sirv public --gzip --brotli

296

297

# Disable compression

298

sirv public --no-gzip --no-brotli

299

300

# Only gzip compression

301

sirv public --gzip --no-brotli

302

```

303

304

### Caching and Performance

305

306

Control caching behavior with ETag and Cache-Control headers.

307

308

**Production vs Development Mode:**

309

310

**Production Mode (default):**

311

- Pre-scans directory and caches file metadata on startup

312

- Serves files from memory cache for maximum performance

313

- Uses `Cache-Control` headers based on `maxAge` and `immutable` settings

314

- File system is only accessed during server initialization

315

316

**Development Mode (`--dev`):**

317

- Reads file system on every request for live updates

318

- Ignores `maxAge` and `immutable` settings

319

- Sets `Cache-Control: no-cache` or `Cache-Control: no-store`

320

- Slower but allows real-time file changes

321

322

**CLI Usage:**

323

324

```bash

325

# Enable ETag headers

326

sirv public --etag

327

328

# Set cache max-age (in seconds)

329

sirv public --maxage 3600

330

331

# Enable immutable cache directive

332

sirv public --maxage 31536000 --immutable

333

334

# Development mode (disables caching optimizations)

335

sirv public --dev

336

```

337

338

**Cache-Control Header Examples:**

339

- `--maxage 3600`: `Cache-Control: public, max-age=3600`

340

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

341

342

### Network Access Control

343

344

Control server accessibility and security.

345

346

**Local-only (default):**

347

348

```bash

349

sirv public # Only accessible from localhost

350

```

351

352

**Network accessible:**

353

354

```bash

355

sirv public --host # Equivalent to --host 0.0.0.0

356

sirv public --host 192.168.1.100 # Bind to specific IP

357

```

358

359

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

360

361

### Logging and Output Control

362

363

Control server logging and console output.

364

365

**CLI Usage:**

366

367

```bash

368

# Quiet mode (no output)

369

sirv public --quiet

370

371

# Disable request logging only

372

sirv public --logs false

373

374

# Development mode with enhanced logging

375

sirv public --dev

376

```

377

378

**Log Format:**

379

```

380

[14:32:15] 200 ─ 1.23ms ─ /index.html

381

[14:32:15] 404 ─ 0.45ms ─ /missing.js

382

```

383

384

## Error Handling

385

386

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

387

388

**HTTP/2 Requirements:**

389

- Validates Node.js version (8.4.0+)

390

- Requires both `--key` and `--cert` for HTTP/2

391

- Validates certificate file existence

392

393

**Port Management:**

394

- Automatically finds alternative port if specified port is taken

395

- Shows port change notification in output

396

397

**SSL Certificate Handling:**

398

- Reads certificate files from file system

399

- Supports passphrase-protected keys

400

- Handles CA certificate chains

401

402

**Common Error Messages:**

403

404

```bash

405

# HTTP/2 version error

406

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

407

408

# Missing SSL certificates

409

ERROR: HTTP/2 requires "key" and "cert" values

410

411

# File system errors for certificates handled internally

412

```

413

414

## Integration Patterns

415

416

### Development Workflow

417

418

```bash

419

# Development with live reloading indicators

420

sirv src --dev --host --cors --single

421

422

# API proxy development (combine with proxy tools)

423

sirv build --port 3000 --cors # Frontend

424

# Proxy /api/* to localhost:8000 (backend)

425

```

426

427

### Production Deployment

428

429

```bash

430

# Production-optimized serving

431

sirv build \

432

--http2 \

433

--key /path/to/server.key \

434

--cert /path/to/server.crt \

435

--gzip \

436

--brotli \

437

--maxage 31536000 \

438

--immutable \

439

--quiet

440

```

441

442

### CI/CD Integration

443

444

```bash

445

# Preview builds in CI

446

sirv dist --port 8080 --quiet &

447

SERVER_PID=$!

448

# Run tests against localhost:8080

449

kill $SERVER_PID

450

```

451

452

## Types

453

454

```javascript { .api }

455

// Environment variables interface

456

interface EnvironmentOverrides {

457

HOST?: string; // Hostname override

458

PORT?: string; // Port number override (as string)

459

}

460

461

// Server configuration options

462

interface ServerOptions {

463

port?: number; // Port to bind

464

host?: string; // Hostname to bind

465

cors?: boolean; // Enable CORS headers

466

http2?: boolean; // Enable HTTP/2 protocol

467

key?: string; // SSL key file path

468

cert?: string; // SSL certificate file path

469

cacert?: string; // CA certificate file path

470

pass?: string; // SSL key passphrase

471

logs?: boolean; // Enable request logging

472

quiet?: boolean; // Suppress output messages

473

clear?: boolean; // Clear console on startup

474

ssl?: boolean; // Enable SSL

475

m?: number; // Cache max-age value

476

}

477

478

// CLI option mapping (internal)

479

interface CLIOptions extends ServerOptions {

480

dev?: boolean; // Development mode

481

etag?: boolean; // Enable ETag headers

482

dotfiles?: boolean; // Serve dotfiles

483

gzip?: boolean; // Enable gzip compression

484

brotli?: boolean; // Enable brotli compression

485

maxage?: number; // Cache-Control max-age

486

immutable?: boolean;// Cache-Control immutable

487

single?: boolean; // SPA mode

488

ignores?: string; // SPA ignore patterns

489

}

490

```