express, hapi, koa, and micro are all popular Node.js frameworks used to build web servers and APIs, but they differ significantly in architecture, philosophy, and feature sets. express is the most widely adopted, offering a minimalist, unopinionated core with a massive ecosystem of middleware. hapi provides a rich, configuration-driven approach with built-in features for validation, caching, and security, favoring convention over code. koa, created by the Express team, modernizes the stack by leveraging async/await and removing callback-based middleware, offering a more elegant flow control. micro takes an extreme minimalist approach, focusing solely on building small, composable microservices with a functional programming style, relying heavily on native Node.js features.
When building backend services in Node.js, the choice of framework dictates your application's structure, error handling strategy, and long-term maintainability. While express, hapi, koa, and micro all serve HTTP requests, their underlying architectures solve common problems in fundamentally different ways. Let's examine how they handle routing, middleware flow, error management, and extensibility.
How you define URL paths and handle incoming requests varies from implicit conventions to explicit configuration.
express uses imperative method chaining to define routes directly on the app instance. It is straightforward but can become unwieldy in large files without manual organization.
// express: Imperative route definition
const express = require('express');
const app = express();
app.get('/users/:id', (req, res) => {
res.json({ id: req.params.id });
});
app.listen(3000);
hapi relies on a configuration object approach. Routes are defined in an array with explicit properties for method, path, and handler, promoting a clear separation of concerns.
// hapi: Configuration-based routes
const Hapi = require('@hapi/hapi');
const init = async () => {
const server = Hapi.server({ port: 3000 });
server.route({
method: 'GET',
path: '/users/{id}',
handler: (request, h) => {
return { id: request.params.id };
}
});
await server.start();
};
init();
koa does not include a router in its core. You must install a separate router package (like @koa/router), keeping the core library small but requiring extra setup.
// koa: External router required
const Koa = require('koa');
const Router = require('@koa/router');
const app = new Koa();
const router = new Router();
router.get('/users/:id', (ctx) => {
ctx.body = { id: ctx.params.id };
});
app.use(router.routes());
app.listen(3000);
micro has no built-in routing system. It expects you to parse the URL manually or use a helper like micro-fork or path-to-regexp to dispatch logic based on the request URL.
// micro: Manual URL parsing
const { parse } = require('url');
const micro = require('micro');
const server = micro(async (req, res) => {
const { pathname } = parse(req.url);
if (pathname.startsWith('/users/')) {
const id = pathname.split('/')[2];
return { id };
}
return { error: 'Not found' };
});
server.listen(3000);
The mechanism for executing logic before or after a request reaches the handler is where these frameworks diverge most sharply.
express uses a linear middleware stack based on callbacks. You must explicitly call next() to pass control to the next function; forgetting to do so hangs the request.
// express: Callback-based middleware with next()
app.use((req, res, next) => {
console.log('Time:', Date.now());
next(); // Must call next() to continue
});
app.get('/', (req, res) => {
res.send('Hello');
});
hapi uses an extension point system (onRequest, pre, onResponse) rather than a free-form middleware stack. This enforces a structured lifecycle but offers less ad-hoc flexibility.
// hapi: Extension points in lifecycle
server.ext('onRequest', (request, h) => {
request.log('info', 'Request received');
return h.continue; // Explicitly continue
});
server.route({
method: 'GET',
path: '/',
handler: (request, h) => 'Hello'
});
koa introduces a "downstream-upstream" flow using async/await. Middleware functions wrap around the next function, allowing logic to run both before and after the downstream middleware completes naturally.
// koa: Async/await composition
app.use(async (ctx, next) => {
console.log('Start:', Date.now());
await next(); // Waits for downstream to finish
console.log('End:', Date.now());
});
app.use(async (ctx) => {
ctx.body = 'Hello';
});
micro does not have a middleware stack. Instead, it encourages composing small, single-purpose functions. You wrap your main handler with higher-order functions to achieve similar effects.
// micro: Function composition
const withLogging = (handler) => async (req, res) => {
console.log('Start:', Date.now());
const result = await handler(req, res);
console.log('End:', Date.now());
return result;
};
const handler = withLogging(async (req, res) => {
return { hello: 'world' };
});
How errors are caught and returned to the client differs from automatic catches to manual try/catch blocks.
express requires a special error-handling middleware with four arguments (err, req, res, next). If you forget this signature, errors will not be caught.
// express: Special error middleware signature
app.get('/fail', (req, res, next) => {
next(new Error('Something broke'));
});
app.use((err, req, res, next) => {
res.status(500).json({ error: err.message });
});
hapi handles errors by returning an error object or throwing within the handler. The framework automatically catches these and formats the response based on configuration.
// hapi: Throw or return error objects
server.route({
method: 'GET',
path: '/fail',
handler: (request, h) => {
throw new Error('Something broke'); // Caught automatically
}
});
koa leverages native try/catch blocks due to its async/await foundation. Any error thrown in downstream middleware bubbles up and can be caught in a central middleware.
// koa: Native try/catch in context
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
ctx.status = 500;
ctx.body = { error: err.message };
}
});
app.use(async (ctx) => {
throw new Error('Something broke');
});
micro treats errors as rejected Promises. If your async handler throws or returns a rejected promise, micro automatically sends a 500 response with the error message.
// micro: Rejected promises handled automatically
const server = micro(async (req, res) => {
throw new Error('Something broke'); // Returns 500 automatically
});
The philosophy of "batteries included" versus "minimal core" determines how much you need to install separately.
express provides almost nothing out of the box besides routing. You must install separate packages for body parsing, validation, and security headers.
// express: Requires external middleware
const bodyParser = require('body-parser');
app.use(bodyParser.json()); // Not built-in
hapi includes input validation (via joi), caching, authentication schemes, and CORS handling as core features. This reduces dependency count but increases initial learning curve.
// hapi: Built-in validation
server.route({
method: 'POST',
path: '/user',
options: {
validate: {
payload: {
name: Joi.string().required()
}
}
},
handler: (request) => request.payload
});
koa strips away everything, including body parsing. You must explicitly add middleware for common tasks, giving you full control over what runs.
// koa: Body parser is external
const bodyParser = require('koa-bodyparser');
app.use(bodyParser()); // Must be added manually
micro assumes you are building a single endpoint. It automatically parses JSON bodies if the content-type matches, but offers no other utilities.
// micro: Auto JSON parsing for simple cases
const { send } = require('micro');
const micro = require('micro');
module.exports = micro(async (req, res) => {
// req is already parsed if Content-Type is application/json
const data = await req;
send(res, 200, data);
});
You need robust input validation, authentication strategies, and detailed logging out of the box.
hapiYou need to get a server running quickly with access to thousands of existing plugins and tutorials.
expressYou want clean, readable code for complex asynchronous flows without callback hell.
koaYou are deploying to AWS Lambda or Vercel and need the smallest possible footprint for a single task.
micro| Feature | express | hapi | koa | micro |
|---|---|---|---|---|
| Philosophy | Minimalist, unopinionated | Configuration-driven, robust | Modern, elegant core | Functional, single-purpose |
| Middleware | Callback-based (next()) | Lifecycle extensions | Async/Await composition | Function wrapping |
| Error Handling | Special 4-arg middleware | Automatic catch & format | Native try/catch | Rejected promise handling |
| Routing | Built-in | Built-in (config) | External package | Manual / External |
| Body Parsing | External (body-parser) | Built-in | External | Auto (JSON only) |
| Best For | General purpose, legacy | Enterprise, high security | Modern apps, complex flows | Microservices, serverless |
Your choice should align with your team's experience and the project's complexity.
If you need stability and ecosystem breadth, express remains the safe default, though it requires discipline to avoid spaghetti code.
If you are building large-scale systems where configuration and security are paramount, hapi pays off in reduced technical debt.
If you value code clarity and modern JavaScript features, koa offers the best developer experience for custom architectures.
If you are building tiny, isolated services, micro removes all distractions, letting you ship faster with less code.
Avoid micro for anything beyond simple endpoints, and be wary of hapi if your team prefers code-over-configuration. For most new greenfield projects today, koa or a modern express setup with strict linting offers the best balance of flexibility and maintainability.
Choose micro only for building simple, stateless microservices or serverless functions where minimal boilerplate is critical. It forces a functional approach where every request is handled by a single async function. Do not use it for complex monolithic applications, as it lacks built-in routing, middleware stacks, and advanced request lifecycle management.
Choose hapi if you prefer a framework that enforces structure and provides robust built-in capabilities for input validation, authentication, and caching. It is well-suited for large enterprise applications where configuration consistency and security defaults are more valuable than raw flexibility. Avoid it if you dislike heavy configuration objects or need a ultra-lightweight footprint.
Choose express if you need a battle-tested, flexible framework with the largest ecosystem of plugins and community support. It is ideal for teams that want to assemble their own architecture from proven components or need to integrate with legacy systems. However, be prepared to manually configure security, validation, and error handling, as the core is intentionally bare-bones.
Choose koa if you want a modern, lightweight foundation that fully embraces async/await for cleaner middleware logic and better error handling. It is perfect for developers who find Express's callback-style middleware cumbersome but still want the freedom to pick their own routing and validation libraries. Note that it does not include a router or body parser out of the box.
async and awaitDisclaimer: Micro was created for use within containers and is not intended for use in serverless environments. For those using Vercel, this means that there is no requirement to use Micro in your projects as the benefits it provides are not applicable to the platform. Utility features provided by Micro, such as json, are readily available in the form of Serverless Function helpers.
Important: Micro is only meant to be used in production. In development, you should use micro-dev, which provides you with a tool belt specifically tailored for developing microservices.
To prepare your microservice for running in the production environment, firstly install micro:
npm install --save micro
Create an index.js file and export a function that accepts the standard http.IncomingMessage and http.ServerResponse objects:
module.exports = (req, res) => {
res.end('Welcome to Micro');
};
Micro provides useful helpers but also handles return values – so you can write it even shorter!
module.exports = () => 'Welcome to Micro';
Next, ensure that the main property inside package.json points to your microservice (which is inside index.js in this example case) and add a start script:
{
"main": "index.js",
"scripts": {
"start": "micro"
}
}
Once all of that is done, the server can be started like this:
npm start
And go to this URL: http://localhost:3000 - 🎉
micro - Asynchronous HTTP microservices
USAGE
$ micro --help
$ micro --version
$ micro [-l listen_uri [-l ...]] [entry_point.js]
By default micro will listen on 0.0.0.0:3000 and will look first
for the "main" property in package.json and subsequently for index.js
as the default entry_point.
Specifying a single --listen argument will overwrite the default, not supplement it.
OPTIONS
--help shows this help message
-v, --version displays the current version of micro
-l, --listen listen_uri specify a URI endpoint on which to listen (see below) -
more than one may be specified to listen in multiple places
ENDPOINTS
Listen endpoints (specified by the --listen or -l options above) instruct micro
to listen on one or more interfaces/ports, UNIX domain sockets, or Windows named pipes.
For TCP (traditional host/port) endpoints:
$ micro -l tcp://hostname:1234
For UNIX domain socket endpoints:
$ micro -l unix:/path/to/socket.sock
For Windows named pipe endpoints:
$ micro -l pipe:\\.\pipe\PipeName
async & awaitMicro is built for usage with async/await.
const sleep = require('then-sleep');
module.exports = async (req, res) => {
await sleep(500);
return 'Ready!';
};
When you want to set the port using an environment variable you can use:
micro -l tcp://0.0.0.0:$PORT
Optionally you can add a default if it suits your use case:
micro -l tcp://0.0.0.0:${PORT-3000}
${PORT-3000} will allow a fallback to port 3000 when $PORT is not defined.
Note that this only works in Bash.
For parsing the incoming request body we included an async functions buffer, text and json
const { buffer, text, json } = require('micro');
module.exports = async (req, res) => {
const buf = await buffer(req);
console.log(buf);
// <Buffer 7b 22 70 72 69 63 65 22 3a 20 39 2e 39 39 7d>
const txt = await text(req);
console.log(txt);
// '{"price": 9.99}'
const js = await json(req);
console.log(js.price);
// 9.99
return '';
};
buffer(req, { limit = '1mb', encoding = 'utf8' })text(req, { limit = '1mb', encoding = 'utf8' })json(req, { limit = '1mb', encoding = 'utf8' })async function that can be run with await.limit is how much data is aggregated before parsing at max. Otherwise, an Error is thrown with statusCode set to 413 (see Error Handling). It can be a Number of bytes or a string like '1mb'.Error is thrown with statusCode set to 400 (see Error Handling)For other types of data check the examples
So far we have used return to send data to the client. return 'Hello World' is the equivalent of send(res, 200, 'Hello World').
const { send } = require('micro');
module.exports = async (req, res) => {
const statusCode = 400;
const data = { error: 'Custom error message' };
send(res, statusCode, data);
};
send(res, statusCode, data = null)require('micro').send.statusCode is a Number with the HTTP status code, and must always be supplied.data is supplied it is sent in the response. Different input types are processed appropriately, and Content-Type and Content-Length are automatically set.
Stream: data is piped as an octet-stream. Note: it is your responsibility to handle the error event in this case (usually, simply logging the error and aborting the response is enough).Buffer: data is written as an octet-stream.object: data is serialized as JSON.string: data is written as-is.400 error is thrown. See Error Handling.You can use Micro programmatically by requiring Micro directly:
const http = require('http');
const serve = require('micro');
const sleep = require('then-sleep');
const server = new http.Server(
serve(async (req, res) => {
await sleep(500);
return 'Hello world';
}),
);
server.listen(3000);
require('micro').serve.(req, res) => void signature. That uses the provided function as the request handler.await. So it can be asyncrequire('micro').sendError.error.statusCode.error.message as the body.console.error and during development (when NODE_ENV is set to 'development') also sent in responses.throw.require('micro').createError.statusCode.orig sets error.originalError which identifies the original error (if any).Micro allows you to write robust microservices. This is accomplished primarily by bringing sanity back to error handling and avoiding callback soup.
If an error is thrown and not caught by you, the response will automatically be 500. Important: Error stacks will be printed as console.error and during development mode (if the env variable NODE_ENV is 'development'), they will also be included in the responses.
If the Error object that's thrown contains a statusCode property, that's used as the HTTP code to be sent. Let's say you want to write a rate limiting module:
const rateLimit = require('my-rate-limit');
module.exports = async (req, res) => {
await rateLimit(req);
// ... your code
};
If the API endpoint is abused, it can throw an error with createError like so:
if (tooMany) {
throw createError(429, 'Rate limit exceeded');
}
Alternatively you can create the Error object yourself
if (tooMany) {
const err = new Error('Rate limit exceeded');
err.statusCode = 429;
throw err;
}
The nice thing about this model is that the statusCode is merely a suggestion. The user can override it:
try {
await rateLimit(req);
} catch (err) {
if (429 == err.statusCode) {
// perhaps send 500 instead?
send(res, 500);
}
}
If the error is based on another error that Micro caught, like a JSON.parse exception, then originalError will point to it. If a generic error is caught, the status will be set to 500.
In order to set up your own error handling mechanism, you can use composition in your handler:
const { send } = require('micro');
const handleErrors = (fn) => async (req, res) => {
try {
return await fn(req, res);
} catch (err) {
console.log(err.stack);
send(res, 500, 'My custom error!');
}
};
module.exports = handleErrors(async (req, res) => {
throw new Error('What happened here?');
});
Micro makes tests compact and a pleasure to read and write. We recommend Node TAP or AVA, a highly parallel test framework with built-in support for async tests:
const http = require('http');
const { send, serve } = require('micro');
const test = require('ava');
const listen = require('test-listen');
const fetch = require('node-fetch');
test('my endpoint', async (t) => {
const service = new http.Server(
serve(async (req, res) => {
send(res, 200, {
test: 'woot',
});
}),
);
const url = await listen(service);
const response = await fetch(url);
const body = await response.json();
t.deepEqual(body.test, 'woot');
service.close();
});
Look at test-listen for a function that returns a URL with an ephemeral port every time it's called.
npm linknpm link micro. Instead of the default one from npm, node will now use your clone of Micro!You can run the tests using: npm test.
Thanks to Tom Yandell and Richard Hodgson for donating the name "micro" on npm!