Koa-static is a middleware for the Koa web framework designed to efficiently serve static files such as HTML, CSS, JavaScript, images, and other assets. It acts as a wrapper around `koa-send`, providing a streamlined interface for common static file serving patterns. The current stable version is 5.0.0. This package is mature and stable, with infrequent releases (v5.0.0 published 8 years ago), indicating a solid and well-understood functionality rather than rapid ongoing development. Key features include comprehensive caching controls via `maxage`, support for serving hidden files, configurable default index filenames (e.g., `index.html`), and automatic Gzip/Brotli compression where supported by the client. It also offers a `defer` option to allow other middleware to handle requests first and the ability to set custom response headers. Its primary differentiator is its deep integration and idiomatic usage within the Koa ecosystem, offering a lightweight and unopinionated approach compared to more feature-rich alternatives like `koa-static-cache` which offer in-memory caching or complex routing extensions.
npm install koa-staticVerified import paths — ran on the pinned version, not inferred.
Demonstrates how to set up a basic Koa application to serve static files from a 'public' directory with caching and compression enabled. It includes both ESM setup and a simple fallback route.
Ensure your Koa application and all middleware are compatible with Koa 2.x's async/await signature. For `koa-static`, upgrade to v5.0.0 or later. Update middleware functions from `function*` to `async/await` syntax.
Use `koa-mount` to mount `koa-static` to a specific path:
`import mount from 'koa-mount';
app.use(mount('/assets', serve(publicPath)));`If static files should always be served first, ensure `defer` is `false` (the default) or remove the option. If you want other middleware to take precedence, set `defer: true`.
Use `import.meta.url` along with `path` and `fileURLToPath` to construct `__dirname` and `__filename` equivalents:
`import { fileURLToPath } from 'url';
import path from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);`Verify that the file exists in the directory provided to `koa-static`. Ensure the `publicPath` is resolved correctly (e.g., `path.join(__dirname, 'public')`). If serving from a subpath, use `koa-mount`.
Always pass the absolute path to your static files directory as the first argument to `koa-static`: `app.use(serve(path.join(__dirname, 'public')));`
Ensure all files intended to be served statically are located within the `root` directory specified in `koa-static`. Adjust your application's file structure or URL routing accordingly.