Search code examples
javascriptnode.jskoa

Using 'koa-static', app.use(serve('public')) throws a “requires a generator function” error msg


var serve = require('koa-static');
var koa = require('koa');
var app = koa();                              
app.use(serve(__dirname + '/public')); 

Error I am getting is

AssertionError: app.use() requires a generator function

Example over here shows to use this way https://www.npmjs.com/package/koa-static


Solution

  • This is probably happening because you're using the old Koa v1, which uses generator functions for middleware. By default, a lot of middleware has now switched to support Koa v2, and if you want to use it with Koa v1 you will need to install the right version of that middleware.

    In this case, you can just do:

    npm install koa-static@2
    

    to install the older version of koa-static that supports Koa v1. In general, it's a good idea to check out the GitHub repository of the middleware in order to see which versions you can install by looking at the available branches.