Registry / web-framework / koa-static

koa-static

JSON →
library5.0.0jsnpmunverified

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-static
INSTALL
IMPORT
SIG · KOA-STATIC
K
koa-static
web-frameworkjavascriptv5.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

serve
import serve from 'koa-static';
import { serve } from 'koa-static';
Koa-static exports a default function, not a named export. Ensure 'type': 'module' in package.json for ESM.
serve (CommonJS)
const serve = require('koa-static');
Standard CommonJS import. This is often used in older Koa applications or environments not configured for ESM.
Options Interface (TypeScript)
import Koa from 'koa'; import serve, { Options } from 'koa-static'; const options: Options = { maxage: 3600000 };
import Koa from 'koa'; import serve from 'koa-static'; const options: koaStatic.Options = { maxage: 3600000 };
TypeScript users can import the `Options` interface directly for type safety. No direct type definitions are shipped with `koa-static` itself, but `@types/koa-static` provides them, which typically exports `Options` from the main module.

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.

import Koa from 'koa'; import serve from 'koa-static'; import path from 'path'; import { fileURLToPath } from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const app = new Koa(); const publicPath = path.join(__dirname, 'public'); // Create a 'public' directory in your project root and add some files (e.g., index.html) // Example public/index.html: // <h1>Hello from Koa Static!</h1> app.use(serve(publicPath, { // Optional: Enable gzip compression if client supports it and .gz file exists gzip: true, // Optional: Cache assets in browser for 7 days maxage: 1000 * 60 * 60 * 24 * 7, // Optional: Serve 'index.html' when root path is requested index: 'index.html' })); // Fallback for non-static routes app.use(async (ctx) => { if (!ctx.response.status || ctx.response.status === 404) { ctx.body = 'Hello Koa! No static file found or served.'; } }); const PORT = process.env.PORT ?? 3000; app.listen(PORT, () => { console.log(`Koa static server running on http://localhost:${PORT}`); console.log(`Serving files from: ${publicPath}`); });
Debug
Known issues
breakingUpgrading from Koa 1.x (generator-based middleware) to Koa 2.x (async/await middleware) requires updating `koa-static` to a compatible version (v5.x). The middleware signature changed from `function* (next)` to `async (ctx, next) => { ... }`. Direct usage of `koa-static` in a Koa 1.x application will lead to errors.
fix
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.
affects: <5.0.0
gotchaTo serve static files from a specific URL subpath (e.g., `/assets`), `koa-static` must be combined with `koa-mount`. Directly passing a path like `app.use(serve('/assets', publicPath))` will not mount it correctly.
fix
Use `koa-mount` to mount `koa-static` to a specific path:
`import mount from 'koa-mount';
app.use(mount('/assets', serve(publicPath)));`
affects: >=1.0.0
gotchaThe `defer` option, when set to `true`, ensures that `koa-static` only attempts to serve files *after* all downstream middleware have had a chance to respond. If a downstream middleware handles the request, `koa-static` will be skipped. This can be unexpected if you intend static files to be served first.
fix
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`.
affects: >=1.0.0
gotchaWhen using `koa-static` in an ESM project (with `"type": "module"` in `package.json`), ensure your path resolution for the root directory is correct. Node.js's native `__dirname` and `__filename` are not available in ESM modules.
fix
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);`
affects: >=5.0.0
Errors
Common errors & fixes
GET http://localhost:3000/app.js net::ERR_ABORTED 404 (Not Found)
The requested static file (e.g., `app.js`) does not exist in the configured static directory, or the path to the static directory is incorrect, or `koa-static` is not mounted correctly.
fix
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`.
Error: "root" is required in koa-send
The `root` directory parameter (the path to the folder containing your static files) was not provided to `koa-static`.
fix
Always pass the absolute path to your static files directory as the first argument to `koa-static`:
`app.use(serve(path.join(__dirname, 'public')));`
Cannot serve files outside the 'root' directory.
Attempting to access a file via a URL that resolves to a path outside the configured `root` directory for security reasons.
fix
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.
Upgrade
Version history
5.0.0latest on npm
Audit
Dependencies
koarequiredPeer dependency, as it's a Koa middleware. Requires Koa 2.x or later for async/await middleware signature.
koa-sendrequiredRuntime dependency; `koa-static` is a wrapper around `koa-send` for core file serving logic.
Agent activity
2 hits · last 30 days
node
2
Resources
koa-static — npm install koa-static · libregistry