Integrate Sentry (Instrumentation) with Medusa
In this tutorial, you'll learn how to integrate Sentry with your Medusa application to monitor performance and track errors effectively.
When you install a Medusa application, you get a fully-fledged commerce platform with a Framework for customization. An essential part of building customizations is tracking errors in them and ensuring they have good performance.
Medusa facilitates error tracking and performance monitoring by integrating with instrumentation tools like Sentry. Sentry provides real-time tracking of errors and performance issues in your application, allowing you to identify and fix them quickly.
In this tutorial, you'll integrate Sentry with Medusa to monitor your application's performance and errors.
Summary#
By following this tutorial, you'll learn how to:
- Install and set up Medusa.
- Set up instrumentation with Sentry. You'll trace HTTP requests, workflows, Query usages, and database operations.
- Capture HTTP request errors in Sentry.
- Test monitoring and error tracking.
You can follow this tutorial whether you're new to Medusa or an advanced Medusa developer.
Step 1: Install a Medusa Application#
Start by installing the Medusa application on your machine with the following command:
First, you'll be asked for the project's name. Then, when prompted about installing the Next.js Starter Storefront, choose "Yes."
Afterwards, the installation process will start, which will install the Medusa application in a directory with your project's name and the Next.js Starter Storefront in a separate directory named {project-name}-storefront
.
Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credentials and submit the form. Afterwards, you can log in with the new user and explore the dashboard.
Step 2: Set Up Instrumentation with Sentry#
Medusa supports instrumentation and reporting through OpenTelemetry, which allows you to integrate with various monitoring tools, including Sentry. This also gives you the flexibility to switch between different monitoring tools without changing your codebase.
In this step, you'll set up instrumentation in your Medusa application using Sentry.
a. Install Instrumentation Dependencies#
To set up instrumentation in Medusa, you need to install the necessary OpenTelemetry dependencies.
In your Medusa application's directory, run the following command:
Then, you need to install the dependencies necessary for the monitoring tool you want to use, which is Sentry in this case.
So, run the following command to install the necessary Sentry dependencies:
b. Configure Instrumentation#
Now that you have the necessary dependencies installed, you need to configure instrumentation in your Medusa application.
You can configure instrumentation in a special instrumentation.ts
file at the root of your Medusa application. The Medusa application automatically loads this file when it starts.
You should already have a file named instrumentation.ts
in your Medusa application with commented-out code. Replace the file's content with the following:
1import Sentry from "@sentry/node"2import otelApi from "@opentelemetry/api"3import { registerOtel } from "@medusajs/medusa"4import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-grpc" 5import { 6 SentrySpanProcessor, 7 SentryPropagator,8} from "@sentry/opentelemetry-node"9 10Sentry.init({11 dsn: process.env.SENTRY_DSN,12 tracesSampleRate: 1.0,13 // @ts-ignore14 instrumenter: "otel",15})16 17otelApi.propagation.setGlobalPropagator(new SentryPropagator())18 19export function register() {20 registerOtel({21 serviceName: "medusa",22 spanProcessors: [new SentrySpanProcessor()],23 traceExporter: new OTLPTraceExporter(),24 instrument: {25 http: true,26 workflows: true,27 query: true,28 db: true,29 },30 })31}
You first initialize Sentry with your Data Source Name (DSN), which you'll retrieve and set as an environment variable soon. You also set the tracesSampleRate
to 1.0
, which enables tracing in your Sentry project.
Next, you set the global propagator to Sentry's propagator, which allows Sentry to propagate trace context across your application.
Finally, you export a register
function that registers OpenTelemetry. It uses the registerOtel
function from Medusa, which accepts OpenTelemetry configurations with the following custom Medusa options:
serviceName
: The name of your service, which you set to "medusa". You can change it to a more descriptive name if needed.instrument
: An object that specifies what to trace in your Medusa application. You enable tracing for HTTP requests, workflows, Query usages, and database operations by setting their respective properties totrue
.
You can add any additional configurations to either Sentry or OpenTelemetry as needed for your use case.
c. Set Up a Sentry Project#
The final piece to get the Sentry integration working is to set up a Sentry project and get your DSN. The DSN is a unique identifier for your Sentry project that allows your Medusa application to send error and performance data to Sentry.
To set up a Sentry project:
- Log in or sign up to Sentry.
- In your Sentry dashboard, if you're new to Sentry, click the "Start" button. Otherwise, go to Projects from the sidebar and click the "Create Project" button.
- In the "Select Platform" step, select "Node.js" as the platform, then select "Node, Vanilla" in the pop-up.
- In the "Configure Node.js SDK" step, you can find your DSN in the second code block. Copy the DSN, as you'll need it in the next step.
You can skip onboarding or the next steps for now. You'll test out the integration in the next step.
Then, add the following environment variable to your .env
file in your Medusa application:
Replace your_sentry_dsn_here
with the DSN you copied from Sentry.
Test Tracing in Sentry#
You can now test the integration to ensure operations are traced in Sentry.
First, start your Medusa application by running the following command in your Medusa application's directory:
You'll find in the terminal the following message:
This message indicates that OpenTelemetry has been successfully registered and instrumentation is set up successfully.
Then, open your Medusa Admin dashboard in your browser at http://localhost:9000/app
and log in with the user you created earlier.
You can already find the database, workflow executions, and HTTP requests traced in your Sentry project:
- In your Sentry dashboard, go to Explore → Traces from the sidebar.
- You'll find a list of traces on this page, including HTTP requests made to log in to the Medusa Admin dashboard.
If you click on a trace, you can see more details about the trace. For example, if you click on an HTTP request trace, you can see the middlewares and workflows executed, the time taken for each operation, the status of the request, and more.
Test Tracing for Customizations#
Tracing also works for your custom API routes, workflow executions, Query usages, and database operations.
In this section, you'll test it by creating a custom API route that throws an error. For now, you'll only view its tracing in Sentry. Later, you'll configure capturing HTTP request errors in Sentry.
An API route is created in a route.ts
file under a sub-directory of the src/api
directory. The path of the API route is the file's path relative to src/api
.
So, to create an API route at the path /test-sentry
, create the file src/api/test-sentry/route.ts
with the following content:
1import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"2import { MedusaError } from "@medusajs/framework/utils"3 4export async function GET(5 req: MedusaRequest,6 res: MedusaResponse7) {8 throw new MedusaError(9 MedusaError.Types.UNEXPECTED_STATE,10 "This is a test error for Sentry integration."11 )12}
Since you export a GET
route handler function, you expose a GET
API route at /test-sentry
. The route handler function accepts two parameters:
- A request object with details and context on the request, such as body parameters.
- A response object to manipulate and send the response.
In the route handler, you throw a MedusaError
with a custom message. This error will be returned as a response to the request. Later, when you configure error capturing in Sentry, this error will be captured and displayed in the Sentry dashboard.
To test the API route, make sure your Medusa application is running, then go to http://localhost:9000/test-sentry
in your browser or use curl
:
You'll receive the following error in the response:
If you refresh the Tracing page in your Sentry dashboard, you should see a new trace for the /test-sentry
API route.
If you click on the Trace ID, you'll see the details of the trace.
Step 3: Capture HTTP Request Errors in Sentry#
In the previous step, you tested tracing in Sentry by creating a custom API route that throws an error. However, the error was not captured by Sentry. So, you couldn't see the error details in the Sentry dashboard or get notified about it.
In this step, you'll capture HTTP request errors in Sentry. You'll do that by customizing Medusa's default error handler that is used to handle errors in API routes.
To customize the error handler, create the file src/api/middlewares.ts
with the following content:
1import { 2 defineMiddlewares, 3 errorHandler, 4 MedusaNextFunction, 5 MedusaRequest, 6 MedusaResponse,7} from "@medusajs/framework/http"8import { MedusaError } from "@medusajs/framework/utils"9import * as Sentry from "@sentry/node"10 11const originalErrorHandler = errorHandler()12 13export default defineMiddlewares({14 errorHandler: (15 error: MedusaError | any, 16 req: MedusaRequest, 17 res: MedusaResponse, 18 next: MedusaNextFunction19 ) => {20 Sentry.captureException(error)21 return originalErrorHandler(error, req, res, next)22 },23})
You export the defineMiddlewares
function that allows you to apply middlewares and customize Medusa's default error handler.
The function accepts an object with the errorHandler
property, whose value is a custom function that handles errors thrown in API routes.
In the custom error handler, you first capture the error in Sentry using Sentry.captureException(error)
. This allows Sentry to track the error and its context.
Then, you call the original error handler function that Medusa uses to handle errors in API routes. By using this function, you retain Medusa's default error handling behavior of returning the error response to the client.
Test Error Capturing in Sentry#
To test out error capturing in Sentry, start the Medusa application if it's not already running:
Then, send a GET
request to the /test-sentry
API route you created earlier:
You'll receive the same error response as before:
If you check the tracing page in your Sentry dashboard, you'll see a new trace for the /test-sentry
API route. Click on it to view the details.
You'll find in the tracing page the thrown error highlighted in red, indicating that it was captured by Sentry.
If you click on the error, you can view more details about it, such as its stack trace, how many times it occurred, its breadcrumbs, and more.
By capturing HTTP request errors in Sentry, you can now monitor and track errors in your Medusa application effectively. You can also set up alerts in Sentry to get notified about critical issues and handle them promptly.
Next Steps#
You've now integrated Sentry with your Medusa application. You can continue using Sentry to monitor your application's performance and track errors.
You can also expand on your Sentry integration by enabling more features, such as:
- Alerts to get notified about critical issues in your application. You can receive alerts via email, Slack, or other channels.
- Profiling to analyze your application's performance and identify bottlenecks.
- User feedback to collect feedback in your frontend from users about their experience with your application.
If you're new to Medusa, check out the main documentation, where you'll get a more in-depth understanding of all the concepts you've used in this guide and more.
To learn more about the commerce features that Medusa provides, check out Medusa's Commerce Modules.
Troubleshooting#
If you encounter issues during your development, check out the troubleshooting guides.
Getting Help#
If you encounter issues not covered in the troubleshooting guides:
- Visit the Medusa GitHub repository to report issues or ask questions.
- Join the Medusa Discord community for real-time support from community members.
- Contact the sales team to get help from the Medusa team.