How to Configure Bugsnag with Koa and serverless-http Running on AWS Lambda
Bugsnag is a great tool for application crash reporting. It supports a wide variety of platforms across mobile, web, and server-side.
I recently integrated Bugsnag into a server-side application developed with Node.js, Koa.js and the serverless-http package to run on AWS Lambda.
Bugsnag provides documentation for integrating with Koa.js and for integrating with Node.js on AWS Lambda but they do not currently provide complete instructions for when you are using both at the same time.
After a few back-and-forths with their technical support they were able to provide instructions that worked. I’m posting their instructions below since it is not yet publicly available on their site.
Essentially, to get this to work you will need to effectively combine both the AWS Lambda and Koa instructions, passing both plugins into Bugsnag.start(). Here’s a simple example:
const serverless = require('serverless-http') Bugsnag.start({ apiKey: 'YOUR_API_KEY', plugins: [BugsnagPluginKoa, BugsnagPluginAwsLambda] }) const app = new Koa() const middleware = Bugsnag.getPlugin('koa') // This must be the first piece of middleware in the stack. // It can only capture errors in downstream middleware app.use(middleware.requestHandler) /* all other middleware and application routes go here */ // This handles any errors that Koa catches app.on('error', middleware.errorHandler) const bugsnagHandler = Bugsnag.getPlugin('awsLambda').createHandler() exports.handler = bugsnagHandler(serverless(app))
The important thing to note here is that we are calling Bugsnag.start() only once, as early on in the startup cycle as possible, and Bugsnag.start() must be called prior to any calls to Bugsnag.getPlugin().
Note: They actually do have a documentation page for Koa.js on AWS Lambda but currently it is largely just a copy of the Node.js on AWS Lambda instructions and is, as of this writing, incomplete. Hopefully it will be updated soon.