npm i koa, Add "type":"module", Get a Server in Ten Lines
Installing Koa
Install Koa with npm, configure your package.json for ES modules, and run a "Hello World" HTTP server using ctx.body in under ten lines.
What you'll learn
- Install Koa 2 with npm
- Enable ES module mode via "type":"module" in package.json
- Write and start a minimal Koa server that returns a text response
Getting a Koa server running takes three steps: create a project, install the package, and write a handful of lines.
Create the Project
mkdir my-koa-app
cd my-koa-app
npm init -y Enable ES Modules
Koa 2 is an ES module package. Add "type": "module" to package.json so
Node treats .js files as ESM:
{
"name": "my-koa-app",
"type": "module",
"version": "1.0.0"
} Install Koa
npm install koa That is the only runtime dependency you need for a basic server — no bundled router, no body parser, nothing else installed automatically.
Hello World
Create server.js:
import Koa from "koa";
const app = new Koa();
app.use(async (ctx) => {
ctx.body = "Hello, Koa!";
});
app.listen(3000, () => {
console.log("Server running at http://localhost:3000");
}); Run it:
node server.js Open http://localhost:3000 in your browser and you will see Hello, Koa!.
Koa automatically sets the status to 200 and the Content-Type to
text/plain when ctx.body is a string.
What Just Happened
app.use() registers a single middleware function. Because there is no router
yet, every request — regardless of path or method — passes through this one
function. Setting ctx.body tells Koa what to send back to the client.
Up Next
Explore the new Koa() application object and its key properties and methods.