new Koa() Is the Hub for Middleware, Settings, and the HTTP Server
The Application Object
The Koa Application object is your entry point to the framework. Learn app.use, app.listen, app.callback, app.keys, app.proxy, and error handling.
What you'll learn
- Use app.use to register middleware functions
- Start an HTTP server with app.listen and app.callback
- Configure signing keys, proxy trust, and application-level error handling
new Koa() constructs the application instance. You wire up every piece of
your server through methods and properties on this object.
app.use — Register Middleware
import Koa from "koa";
const app = new Koa();
app.use(async (ctx, next) => {
console.log(`${ctx.method} ${ctx.path}`);
await next();
}); app.use appends a middleware to the stack in the order it is called. Every
request travels through middleware top to bottom (and back up on the return
path — more on that in the cascading lesson).
app.listen — Start the Server
const server = app.listen(3000, () => {
console.log("Listening on :3000");
}); app.listen(port, [callback]) creates a Node http.Server, binds it to the
port, and returns it. You can pass the server to libraries that expect a raw
Node server (e.g., ws for WebSockets).
app.callback — Use With an Existing Server
If you need to plug Koa into an https or http2 server you already created:
import https from "node:https";
import fs from "node:fs";
const server = https.createServer(
{ key: fs.readFileSync("key.pem"), cert: fs.readFileSync("cert.pem") },
app.callback()
);
server.listen(443); app.keys — Cookie Signing
app.keys = ["a-long-random-secret", "older-secret-for-rotation"]; Koa uses these to sign and verify cookies when you use ctx.cookies.set
with { signed: true }.
app.proxy — Trust Forwarded Headers
app.proxy = true; // honour X-Forwarded-For, X-Forwarded-Proto Set this to true when your server runs behind a reverse proxy such as
nginx or a load balancer so that ctx.ip and ctx.protocol reflect the
real client values.
app.on(‘error’) — Centralised Error Handling
Unhandled errors emitted during a request bubble up to the app’s error
event. Attach a listener to log them without crashing the process:
app.on("error", (err, ctx) => {
console.error("server error", err, ctx);
}); Up Next
Zoom in on the ctx context object that every middleware receives.