Skip to content
koajsPublic

About

Static file server middleware

Resources

Code of conduct

Contributing

Security policy

Stars

1.1k stars

Watchers

15 watching

Forks

Repository files navigation

koa-static

NPM version Build status License Downloads

Koa static file serving middleware, wrapper for koa-send.

Installation

$ npm install koa-static

API

import Koa from "koa"; // CJS: require('koa');
import serve from "koa-static"; // CJS: require('koa-static')
const app = new Koa();
app.use(serve(root, opts));
  • root root directory string. nothing above this root directory can be served
  • opts options object.

CommonJS (require('koa-static')) and ESM default imports are supported on Node.js 22 and newer. TypeScript declarations are included.

Options

  • maxage Browser cache max-age in milliseconds. defaults to 0
  • hidden Allow transfer of hidden files. defaults to false
  • index Default file name, defaults to 'index.html'
  • defer If true, serves after return next(), allowing any downstream middleware to respond first.
  • gzip Try to serve the gzipped version of a file automatically when gzip is supported by a client and if the requested file with .gz extension exists. defaults to true.
  • brotli Try to serve the brotli version of a file automatically when brotli is supported by a client and if the requested file with .br extension exists (note, that brotli is only accepted over https). defaults to true.
  • setHeaders Function to set custom headers on response.
  • extensions Try to match extensions from passed array to search for file when no extension is sufficed in URL. First found is served. (defaults to false). e.g. ['html']

Example

const serve = require("koa-static");
const Koa = require("koa");
const app = new Koa();

// $ GET /package.json
app.use(serve("."));

// $ GET /hello.txt
app.use(serve("test/fixtures"));

// or use absolute paths
app.use(serve(__dirname + "/test/fixtures"));

app.listen(3000);

console.log("listening on port 3000");

See also

Development

Use Node.js 26. Run npm run setup to install dependencies, validate, and install the optional pre-commit hook. Run npm run validate for lint, types, and tests; npm run build emits CommonJS, ESM, and declarations in dist/.

Releases

Push a vX.Y.Z tag matching package.json on a commit already on master to run CI and publish to npm using trusted publishing.

License

MIT

About

Static file server middleware

Resources

Code of conduct

Contributing

Security policy

Stars

1.1k stars

Watchers

15 watching

Forks

Releases

Packages

Used by

Contributors

Languages