Backend Development 11 min read

Getting Started with Koa: A Lightweight Node.js Framework for Building HTTP Servers

This article introduces native Node.js HTTP server creation, explains request and response concepts, and then demonstrates how to use the Koa framework—including installation, middleware, routing, body parsing, and the onion model—to build clean, maintainable backend services.

Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Getting Started with Koa: A Lightweight Node.js Framework for Building HTTP Servers

First, a simple HTTP server is created with Node's built‑in http module, showing how to listen on port 3000, log request headers, and send a response using res.end() . The article explains the difference between request body (data sent from the client) and response body (data returned by the server), and highlights important response headers such as Content‑Length , Content‑Type , Cache‑Control , and Set‑Cookie .

Native Node Development

const http = require('http')
http.createServer((req, res) => {
  console.log(req.headers)
  res.end('后端返回数据 hello world')
}).listen(3000, () => {
  console.log('server is running')
})

To serve different routes, an if statement can be used to check req.url , but this quickly becomes unwieldy for many endpoints.

const http = require('http')
http.createServer((req, res) => {
  if (req.url === '/home') {
    res.end('首页的数据')
  }
}).listen(3000, () => {
  console.log('server is running')
})

Because extensive if‑else chains are hard to maintain, the article introduces Koa as a modern alternative that uses middleware to handle routing more elegantly.

Koa

Basic Syntax

Koa is not built into Node and must be installed via npm.

npm init -y
npm install koa

After installation, Koa can be required and a new application instance created.

const Koa = require('koa')
const app = new Koa()
const main = (ctx) => {
  console.log(ctx.url)
  ctx.body = 'hello world'
}
app.use(main)
app.listen(3000, () => {
  console.log('服务器启动成功')
})

The ctx object contains both request and response information; setting ctx.body defines the response data. To return raw HTML, the response type must be set:

const main = (ctx) => {
  ctx.response.type = 'text'
  ctx.body = '
Hello world
'
}

For serving an HTML file on a specific route, the fs module can be used.

const Koa = require('koa')
const fs = require('fs')
const app = new Koa()
const main = (ctx) => {
  if (ctx.url === '/home') {
    ctx.response.type = 'html'
    ctx.body = fs.readFileSync('./assets/template.html')
  }
}
app.use(main)
app.listen(3000, () => {
  console.log('服务器启动成功')
})

Defining Routes

Koa routing is provided by the @koa/router package.

npm i @koa/router
const Router = require('@koa/router')
const router = new Router()
app.use(router.routes())

An example of a GET route returning JSON data:

const Koa = require('koa')
const app = new Koa()
const Router = require('@koa/router')
const router = new Router()
router.get('/home', (ctx, next) => {
  ctx.body = {
    code: 200,
    msg: 'success',
    data: { name: '张三', age: 20 }
  }
})
app.use(router.routes())
app.listen(3000, () => {
  console.log('服务启动成功')
})

Query parameters can be accessed via ctx.query . For POST requests, the @koa/bodyparser middleware parses the request body.

npm i @koa/bodyparser
const Koa = require('koa')
const app = new Koa()
const Router = require('@koa/router')
const router = new Router()
const { bodyParser } = require('@koa/bodyparser')
app.use(bodyParser())
router.post('/login', (ctx) => {
  const { username, password } = ctx.request.body
  if (username === 'admin' && password === '123') {
    ctx.body = { code: 200, msg: '登录成功', user: username }
  } else {
    ctx.body = { code: 401, msg: '账号或密码错误' }
  }
})
app.use(router.routes())
app.listen(3000, () => {
  console.log('服务启动成功')
})

Onion Model

Koa's middleware follows the onion model: each middleware receives ctx and a next function. Calling next() passes control to the next layer, and execution resumes after the downstream middleware finishes.

const Koa = require('koa')
const app = new Koa()
const one = (ctx, next) => { console.log(1); next(); console.log(2) }
const two = (ctx, next) => { console.log(3); next(); console.log(4) }
const three = (ctx, next) => { console.log(5); next(); console.log(6) }
app.use(one)
app.use(two)
app.use(three)
app.listen(3000)

Without calling next() , the chain stops, demonstrating how developers can control request flow.

Overall, Koa provides a concise, middleware‑driven approach to building HTTP services, making backend development faster and more maintainable.

backendJavaScriptmiddlewareNode.jsRoutinghttpKoa
Rare Earth Juejin Tech Community
Written by

Rare Earth Juejin Tech Community

Juejin, a tech community that helps developers grow.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.