Use Connect/Express Middleware in Koa
koa-connect is a utility package that enables the integration of standard Connect or Express middleware into a Koa application. It acts as a bridge, adapting the `(req, res, next)` signature of Connect/Express middleware to Koa's `(ctx, next)` context-based middleware pattern. The current stable version is 2.1.1. While not actively undergoing rapid feature development, the package is in a maintenance state, receiving updates for compatibility and bug fixes as needed. It serves a niche purpose, primarily when a Koa-native version of a required middleware is unavailable or for library authors aiming for framework-agnostic HTTP middleware. Developers are strongly cautioned to prefer Koa-specific middleware when available due to fundamental design differences between Koa's async/await flow and Express's callback-based approach, which can lead to unexpected behavior and control flow issues.
Common errors
-
TypeError: res.send is not a function
cause An Express-style middleware adapted by `koa-connect` is attempting to use `res.send()`, which is an Express-specific method and not available on the native Node.js `http.ServerResponse` object provided within Koa's context.fixModify the Express middleware to use standard Node.js `res.end()` or `res.write()` methods, or ensure `ctx.body` is set in a subsequent Koa middleware after the adapted middleware has processed the request. -
Request hangs indefinitely or subsequent Koa middleware are not executed.
cause The adapted Connect/Express middleware did not call the `next()` function, preventing the Koa middleware chain from proceeding to the next handler.fixReview the Connect/Express middleware's implementation and ensure `next()` is invoked correctly to pass control to the subsequent middleware in the Koa application.
Warnings
- gotcha It is highly recommended to use Koa-specific middleware instead of converting an Express version when Koa-native alternatives are available. Koa and Express have fundamentally different designs (async/await vs. callback-based), and `koa-connect` is a workaround, not a seamless replacement, which can lead to unexpected behavior and control flow issues.
- gotcha When adapting an Express-style middleware, you *must* explicitly declare and invoke the `next` callback parameter within the middleware function for the Koa chain to continue. Failure to call `next()` will halt the request processing at the adapted middleware.
- gotcha When writing framework-agnostic middleware intended for use with `koa-connect`, avoid using Express-dependent APIs (e.g., `res.send()`, `req.params`, `req.body`) as these are not part of the standard Node.js `http` module and will not be available or function correctly within Koa's context.
Install
-
npm install koa-connect -
yarn add koa-connect -
pnpm add koa-connect
Imports
- c2k
const c2k = require('koa-connect');import c2k from 'koa-connect';
- c2k
const c2k = require('koa-connect'); - MiddlewareAdapter
import type { MiddlewareAdapter } from 'koa-connect';
Quickstart
const Koa = require('koa');
const c2k = require('koa-connect');
// A generic Express-style middleware function
function connectMiddleware(req, res, next) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('From the Connect middleware');
next(); // Crucial to call next to continue the Koa chain
}
// A basic Koa middleware to illustrate the flow
async function koaGreetingMiddleware(ctx, next) {
console.log('Koa middleware: Before calling next');
await next(); // Proceed to downstream middleware
console.log('Koa middleware: After downstream middleware');
}
const app = new Koa();
app.use(koaGreetingMiddleware);
app.use(c2k(connectMiddleware)); // Integrate the Connect middleware
// Final Koa middleware to show control flow continues
app.use(async (ctx, next) => {
if (ctx.path === '/') {
ctx.body = ctx.body || 'Hello from Koa after Connect!';
}
await next();
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});