Using express middleware in koa

urish picture urish · Aug 19, 2014 · Viewed 7.3k times · Source

I have existing code which implements an express middleware. How can I use this middleware in a Koa application?

When I try to call app.use(expressMiddleware) in order to use the middleware in my Koa app, Koa complains that a generator function is required:

AssertionError: app.use() requires a generator function

So I guess that some kind of adapter or trick is needed here... ideas?

Answer

Tomas Holas picture Tomas Holas · May 8, 2015

Also, you can try koa-connect: https://github.com/vkurchatkin/koa-connect

It looks quite straightforward:

var koa = require('koa');
var c2k = require('koa-connect');
var app = koa();

function middleware (req, res, next) {
  console.log('connect');
  next();
}

app.use(c2k(middleware));

app.use(function * () {
  this.body = 'koa';
});

app.listen(3000);