#strapi#sentry

Integrate Sentry With Strapi

Sujay Prabhu's avatar

Sujay Prabhu

Sentry is a platform that notifies exceptions or errors that a user runs into while using the application. It can also be used for performance monitoring, setting alerts of errors and monitoring the health of each releases. Sentry can be integrated with Strapi in a couple of ways.

Using the official plugin: @strapi/plugin-sentry

  • This is the official Sentry plugin for Strapi which can be used to track errors.
  • Install the plugin using the command:
yarn add @strapi/plugin-sentry // yarn
npm install @strapi/plugin-sentry // npm
  • In order to track error events, we have to enable the plugin by adding it to plugins configuration file i.e. ./config/plugins.js
  sentry: {
    enabled: true,
    config: {
      dsn: process.env.SENTRY_DSN,
      sendMetadata: true,
    },
  }

Here is the link of the pull request for integrating Sentry using officail plugin.

Note: strapi-plugin-sentry was the plugin to be used with Strapi v3 and it is deprecated with Strapi v4

Create custom middleware in Strapi

  • This approach can be used to leverage the benefits of Sentry like performance monitoring, track release health, reporting errors.
  • Initialize the Sentry SDK and capture the exceptions in the custom middleware.
  • Common options that can be passed to SDK are:
    • dsn: Dsn is a unique identifier for the project created in Sentry and it will let SDK know where to log the events.
    • environment: This will set the current environment of the project and this will also help to filter errors or exceptions based on enviroment in Sentry.
    • tracesSampleRate: This will be between 0 and 1 where 0 means 0% and 1 means 100%. This can be used to decide the percentage of transactions that can be logged in Sentry.
// src/middlewares/sentry.js
 
Sentry.init({
  dsn: process.env.SENTRY_DSN,
  environment: strapi.config.environment,
  integrations: [new Sentry.Integrations.Http({ tracing: true })],
  tracesSampleRate: 1.0,
});
 
module.exports = (config, { strapi }) => {
  return async (ctx, next) => {
    try {
      await next();
    } catch (error) {
      // Error object or string can be passed to captureException
      Sentry.captureException(error);
      throw error;
    }
  };
};
  • Once middleware is created, it needs to be added to the middlewares configuration file
// config/middleware.js
 
[
  // ... existing middlewares
  'global::sentry',
];

Here is the link of the pull request for integrating Sentry by creating custom middleware.

Related Articles:

Sentry for Koa

Why Koa?

Middlewares in Strapi