koa-static-server

raw JSON →
1.5.2 verified Sat May 09 auth: no javascript maintenance

Static file serving middleware for Koa with support for directory listing, URL rewriting, and custom index files. Current stable version is 1.5.2. This package provides a simple API for serving static assets in Koa applications, similar to koa-static but with built-in options for rootPath rewriting, notFoundFile fallback, gzip support, and index file customization. It is designed for Koa v1 and may not be compatible with Koa v2 without additional conversion middleware.

error TypeError: serve is not a function
cause Import error: using ESM named import instead of default import or require.
fix
Use default import: import serve from 'koa-static-server'
error Error: Cannot find module 'koa'
cause Missing peer dependency 'koa'. This module requires 'koa' to be installed.
fix
Install koa: npm install koa
error TypeError: app.use() requires a middleware function
cause Passing serve instead of serve() with options. serve is a factory function, not middleware.
fix
Use app.use(serve({ rootDir: 'public' }))
gotcha This package is designed for Koa v1. Using it with Koa v2 requires a converter like 'koa-convert' or 'koa-v1-middleware'. Direct use may cause errors.
fix If using Koa v2, use 'koa-convert' to wrap the middleware: app.use(convert(serve({...})))
gotcha The 'rootPath' option rewrites the URL path. For example, serving rootDir 'web' with rootPath '/admin' means URLs under '/admin' map to files in 'web', not '/admin/web'.
fix Set rootPath to the URL prefix you want, not the filesystem path.
gotcha If no 'index' file is found at the root, the middleware does not send a default response and may call through to downstream middleware. This can cause 404s if not handled.
fix Set 'notFoundFile' option to a fallback file, or ensure an index file exists in rootDir.
deprecated The package has not been updated since 2016 and may have unpatched vulnerabilities. Use 'koa-static' or 'koa-send' instead for modern Koa applications.
fix Migrate to 'koa-static' (v5+) for Koa v2 support and active maintenance.
npm install koa-static-server
yarn add koa-static-server
pnpm add koa-static-server

Sets up a Koa static server serving files from 'public' under '/static' with index file support, caching, and gzip.

const Koa = require('koa');
const serve = require('koa-static-server');
const app = new Koa();
app.use(serve({
  rootDir: 'public',
  rootPath: '/static',
  index: 'index.html',
  maxage: 3600000,
  gzip: true,
  hidden: false
}));
app.listen(3000, () => {
  console.log('Server running on port 3000');
});