Koa is an expressive, robust HTTP middleware framework for Node.js developed by the creators of Express.
Basic Server & Onion Middleware
const Koa = require('koa');
const app = new Koa();
// Logger middleware (cascades forward and backward)
app.use(async (ctx, next) => {
const start = Date.now();
await next(); // Pass control to downstream middleware
const ms = Date.now() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
// Response middleware
app.use(async (ctx) => {
ctx.body = { message: 'Hello from Koa!' };
});
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Context (ctx) Reference
// Request Inspection
ctx.method; // "GET", "POST", etc.
ctx.url; // Full URL path
ctx.query; // Parsed query string object
ctx.headers; // Request headers object
ctx.get('User-Agent'); // Header lookup helper
// Response Construction
ctx.status = 200; // Set HTTP status code
ctx.body = 'Hello'; // String, Buffer, Stream, or JSON Object
ctx.set('X-Custom', 'Value'); // Set response header
ctx.type = 'json'; // Content-Type shorthand
ctx.redirect('/login'); // Send 302 redirect
Centralized Error Handling
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
ctx.status = err.status || 500;
ctx.body = { error: err.message };
ctx.app.emit('error', err, ctx);
}
});
app.on('error', (err, ctx) => {
console.error('Server error:', err);
});