Sirv Static File Server Middleware

3.0.2 · active · verified Wed Apr 22

Sirv is an optimized and lightweight middleware designed for serving static assets in Node.js applications, compatible with frameworks like Polka, Express, and native HTTP/S servers. The current stable version is 3.0.2. Its primary differentiator is a significant performance advantage over alternatives like `serve-static` because it pre-scans and caches file system information upfront (when not in 'dev' mode), avoiding costly per-request file system checks. This makes it very efficient for production deployments. Releases are active, with recent patches and a major version upgrade to v3.0.0 that introduced native ESM support and a higher Node.js baseline. It ships with TypeScript types, enhancing developer experience.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `sirv` with `polka` and `compression` to serve static files from a 'public' directory. It highlights ESM usage, configuration options like `maxAge` and `dev` mode, and shows how to integrate it alongside other middleware. It dynamically creates a 'public' directory and files for immediate execution.

import polka from 'polka';
import sirv from 'sirv';
import compression from 'compression';
import * as path from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const publicDir = path.join(__dirname, 'public');

// Create a dummy 'public' directory and an index.html file for demonstration
import { promises as fs } from 'node:fs';
async function setupPublicDir() {
  await fs.mkdir(publicDir, { recursive: true });
  await fs.writeFile(path.join(publicDir, 'index.html'), '<h1>Hello from Sirv!</h1><p>This is a static file.</p>');
  await fs.writeFile(path.join(publicDir, 'styles.css'), 'body { font-family: sans-serif; background-color: #f0f0f0; }');
}

// Initialize sirv handler
const assets = sirv(publicDir, {
  maxAge: 31536000, // 1 year
  immutable: true,
  gzip: true, // Look for precompiled .gz files
  dotfiles: false, // Don't serve dotfiles
  dev: process.env.NODE_ENV === 'development' // Enable dev mode for caching control
});

const PORT = process.env.PORT ?? 3000;

await setupPublicDir();

polka()
  .use(compression()) // Apply compression before sirv
  .use(assets) // Serve static assets
  .use('/api', (req, res) => {
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({ message: 'This is an API endpoint', timestamp: Date.now() }));
  })
  .listen(PORT, (err) => {
    if (err) throw err;
    console.log(`> Ready on http://localhost:${PORT}!`);
    console.log(`> Serving static files from ${publicDir}`);
  });

view raw JSON →