Koa Static File Server

5.0.0 · maintenance · verified Wed Apr 22

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.

Common errors

Warnings

Install

Imports

Quickstart

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}`);
});

view raw JSON →