Use Connect/Express Middleware in Koa

2.1.1 · active · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

Demonstrates how to integrate a standard Connect/Express-style middleware into a Koa application using `koa-connect`, illustrating the control flow between Koa and adapted middleware.

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');
});

view raw JSON →