Koa Ships Lean — The Ecosystem Fills the Gaps
Third-Party Middleware
Koa bundles almost nothing beyond the core context. This lesson surveys the essential third-party packages — body parsing, CORS, security headers, static files, logging, and compression — and shows how to mount them.
What you'll learn
- Install and configure the six most common Koa middleware packages
- Understand the correct registration order for each package
- Avoid the pitfalls of applying compression or CORS in the wrong position
Koa’s core is intentionally tiny. The team extracted everything non-essential into separate packages so you include only what you need.
koa-bodyparser
Parses JSON, form, and text bodies into ctx.request.body.
npm install koa-bodyparser import bodyParser from 'koa-bodyparser';
app.use(bodyParser());
app.use(async (ctx) => {
console.log(ctx.request.body); // parsed JSON or form data
ctx.body = 'ok';
}); Must be registered before any route that reads ctx.request.body.
@koa/cors
Adds Access-Control-* headers for cross-origin requests.
npm install @koa/cors import cors from '@koa/cors';
app.use(cors({ origin: 'https://myapp.com', credentials: true })); Register early so preflight OPTIONS requests are handled before routes.
koa-helmet
Sets security-related HTTP headers (CSP, HSTS, X-Frame-Options, etc.)
using the same defaults as the Express helmet package.
npm install koa-helmet import helmet from 'koa-helmet';
app.use(helmet()); koa-static
Serves files from a directory.
npm install koa-static import serve from 'koa-static';
app.use(serve('./public')); Can be placed early in the stack to short-circuit asset requests before they reach auth or body-parsing layers.
koa-logger
Logs each request method, URL, status, and response time to stdout.
npm install koa-logger import logger from 'koa-logger';
app.use(logger()); koa-compress
Gzip/Brotli compresses responses transparently.
npm install koa-compress import compress from 'koa-compress';
app.use(compress({ threshold: 2048 })); Register after the error handler but before routes so that error responses are also compressed.
Recommended Mount Order
| # | Package | Reason for position |
|---|---|---|
| 1 | Error handler | Wraps everything |
| 2 | koa-logger | Sees full req/res lifecycle |
| 3 | koa-compress | Compresses all downstream output |
| 4 | koa-helmet | Security before content |
| 5 | @koa/cors | Preflight before routes |
| 6 | koa-static | Short-circuits asset requests |
| 7 | koa-bodyparser | Before routes read body |
| 8 | Routes | Innermost |
Up Next
Sometimes you only want middleware to run for certain paths or methods. The next lesson covers conditional mounting patterns.
Conditional Middleware →