node.jsmiddlewarekoactx

Using ctx in koa middlware


I have a koa middleware that I am using like this:

.use(signS3())

What I want to do now is use the ctx object from koa in the config object from signS3(). I would like to do something like this:

.use((ctx, next) => signS3({ keyPrefix: ctx.host })(ctx, next))

But this doesn't work. I am thinking I have the syntax wrong, would appreciate any input on how to do this.


Solution

  • You are using middleware written for koa@1 which uses generators instead of async/await. You should have noticed this warning when running your application:

    koa deprecated Support for generators will be removed in v3. See the documentation for examples of how to convert old middleware https://github.com/koajs/koa/blob/master/docs/migration.md

    In order to use this middleware in koa@2 you need to convert it, manually or using koa-convert. For example:

    const convert = require('koa-convert');
    
    app.use(
      (ctx, next) => convert(
        signS3({
          bucket: 'MyBucket',
          keyPrefix: ctx.host,
        })
      )(ctx, next)
    );
    

    Also take a look at official documentation about Using v1.x Middleware in v2.x