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.
npm install sirvVerified import paths — ran on the pinned version, not inferred.
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.
Upgrade Node.js to version 18 or higher (e.g., using nvm) or pin sirv to a 2.x version in your `package.json` (e.g., `"sirv": "^2.0.0"`).
Migrate your imports to use ESM syntax: `import sirv from 'sirv';`. Ensure your project is configured for ESM, typically by setting `"type": "module"` in `package.json` or using `.mjs` file extensions.
Ensure `opts.dev` is set to `false` or omitted (default is `false`) for production builds. A common pattern is `dev: process.env.NODE_ENV === 'development'`.
Always provide an absolute path for `dir`, e.g., using `path.resolve(__dirname, 'public')` or `path.join(path.dirname(fileURLToPath(import.meta.url)), 'public')` for ESM.
Ensure your file structure does not have top-level files named identically to your static asset directory (e.g., if `dir` is 'public', do not have a file named 'public' in the root serving directory).
Change `const sirv = require('sirv');` to `import sirv from 'sirv';` and ensure your project uses ES Modules correctly.Verify the `dir` path is absolute and correct. Check if `opts.dotfiles` is `true` for dotfiles, and `opts.extensions` includes the necessary fallback extensions (e.g., `['html']` for `/foo` to find `/foo.html`). Also, ensure file permissions allow Node.js to read the files.
Change the `PORT` variable in your quickstart code to an unused port (e.g., 8080, 5000) or ensure the conflicting process is stopped. You can also use a tool like `lsof -i :<PORT>` on Unix-like systems to identify the process.