How to Add Bugsnag to Strapi v4

Learn how to integrate Bugsnag into a Strapi v4 project via a global middleware function

Bret Cameron
2 min readJul 30, 2022

--

Photo by Neringa Hünnefeld on Unsplash

In this tutorial, we’ll explore how to add Bugsnag to a Strapi project.

Background

Bugsnag is a useful tool for monitoring and reporting bugs.

Strapi is a powerful headless CMS. Its most recent version, v4, introduced significant changes to the structure of the project, meaning that older tutorials (such as this one, for v3) are no longer relevant.

Creating a new Strapi Project

To create a new Strapi project, run:

npx create-strapi-app@latest my-project

Installing Dependencies

Navigate into your new project, and install the following dependencies. Strapi is built using Koa, so we’ll need to use Bugsnag’s Koa plugin.

npm install --save @bugsnag/js @bugsnag/plugin-koa

Adding Bugsnag via a new Middleware

In src/index.js , you’ll see an empty bootstrap function. In here, we can initiate Bugsnag.

async bootstrap({ strapi }) {
Bugsnag.start({
apiKey: process.env.BUGSNAG_KEY,
plugins: [BugsnagPluginKoa],
});
}

Make sure to install your key somewhere safe. In this example, we’ve added a environment variable called BUGSNAG_KEY to our .env file. This can be generated inside the Bugsnag UI (make sure to select the Koa template).

Next, we’ll add a new script to our package.json , which will help us use Strapi’s generate helper.

"scripts": {
"generate": "strapi generate",
// other scripts
}

Now we can run npm run generate . Choose middleware , call it “bugsnag”, and select Add middleware to root of project . You’ll now see a new file has been created atsrc/middlewares/bugsnag.js , which will look something like this:

"use strict";module.exports = (config, { strapi }) => {
return async (ctx, next) => {
strapi.log.info("In bugsnag middleware.");
await next();
};
};

--

--

Bret Cameron

Writer and developer based in London. On Medium, I write about JavaScript and web development 💻