Raw
1 import { Card, Prerequisites, Details, WorkflowDiagram } from "docs-ui"
2 import { Github, PlaySolid } from "@medusajs/icons"
3
4 export const metadata = {
5 title: `Integrate Sentry (Instrumentation) with Medusa`,
6 }
7
8 # {metadata.title}
9
10 In this tutorial, you'll learn how to integrate Sentry with your Medusa application to monitor performance and track errors effectively.
11
12 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.
13
14 Medusa facilitates error tracking and performance monitoring by integrating with instrumentation tools like [Sentry](https://sentry.io/). Sentry provides real-time tracking of errors and performance issues in your application, allowing you to identify and fix them quickly.
15
16 In this tutorial, you'll integrate Sentry with Medusa to monitor your application's performance and errors.
17
18 ## Summary
19
20 By following this tutorial, you'll learn how to:
21
22 - Install and set up Medusa.
23 - Set up instrumentation with Sentry. You'll trace HTTP requests, workflows, Query usages, and database operations.
24 - Capture HTTP request errors in Sentry.
25 - Test monitoring and error tracking.
26
27 You can follow this tutorial whether you're new to Medusa or an advanced Medusa developer.
28
29 ![Diagram showcasing what is traced in Sentry](https://res.cloudinary.com/dza7lstvk/image/upload/v1750069550/Medusa%20Resources/sentry-integration_xb2ior.jpg)
30
31 <Card
32 title="Example Repository"
33 text="Find the full code of the guide in this repository."
34 href="https://github.com/medusajs/examples/tree/main/sentry-integration"
35 icon={Github}
36 />
37
38 ---
39
40 ## Step 1: Install a Medusa Application
41
42 <Prerequisites items={[
43 {
44 text: "Node.js v20.19.0+ or v22.12.0+",
45 link: "https://nodejs.org/en/download"
46 },
47 {
48 text: "Git CLI tool",
49 link: "https://git-scm.com/downloads"
50 },
51 {
52 text: "PostgreSQL",
53 link: "https://www.postgresql.org/download/"
54 }
55 ]} />
56
57 Start by installing the Medusa application on your machine with the following command:
58
59 ```bash
60 npx create-medusa-app@latest
61 ```
62
63 First, you'll be asked for the project's name. Then, when prompted about installing the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx), choose "Yes."
64
65 Afterwards, the installation process will start, which will install the Medusa application as a monorepository in a directory with your project's name. The backend is installed in the `apps/backend` directory, and the Next.js Starter Storefront is installed in the `apps/storefront` directory.
66
67 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.
68
69 <Note title="Ran into Errors?">
70
71 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
72
73 </Note>
74
75 <Note>
76
77 In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project.
78
79 </Note>
80
81 ---
82
83 ## Step 2: Set Up Instrumentation with Sentry
84
85 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.
86
87 In this step, you'll set up instrumentation in your Medusa application using Sentry.
88
89 <Note>
90
91 Refer to the [Instrumentation](!docs!/learn/debugging-and-testing/instrumentation) documentation for more details on how to set up instrumentation in Medusa.
92
93 </Note>
94
95 ### a. Install Instrumentation Dependencies
96
97 To set up instrumentation in Medusa, you need to install the dependencies necessary for the monitoring tool you want to use, which is Sentry in this case.
98
99 So, run the following command to install the necessary Sentry dependencies:
100
101 ```bash npm2yarn
102 npm install @sentry/node @opentelemetry/api @opentelemetry/exporter-trace-otlp-grpc @sentry/opentelemetry-node @opentelemetry/core@1.x @opentelemetry/sdk-trace-base@1.x @opentelemetry/semantic-conventions@1.x
103 ```
104
105 ### b. Configure Instrumentation
106
107 Now that you have the necessary dependencies installed, you need to configure instrumentation in your Medusa application.
108
109 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.
110
111 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:
112
113 ```ts title="instrumentation.ts"
114 import Sentry from "@sentry/node"
115 import otelApi from "@opentelemetry/api"
116 import { registerOtel } from "@medusajs/medusa"
117 import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-grpc"
118 import {
119 SentrySpanProcessor,
120 SentryPropagator,
121 } from "@sentry/opentelemetry-node"
122
123 Sentry.init({
124 dsn: process.env.SENTRY_DSN,
125 tracesSampleRate: 1.0,
126 // @ts-ignore
127 instrumenter: "otel",
128 })
129
130 otelApi.propagation.setGlobalPropagator(new SentryPropagator())
131
132 export function register() {
133 registerOtel({
134 serviceName: "medusa",
135 spanProcessors: [new SentrySpanProcessor()],
136 traceExporter: new OTLPTraceExporter(),
137 instrument: {
138 http: true,
139 workflows: true,
140 query: true,
141 db: true,
142 },
143 })
144 }
145 ```
146
147 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.
148
149 Next, you set the global propagator to Sentry's propagator, which allows Sentry to propagate trace context across your application.
150
151 Finally, you export a `register` function that registers OpenTelemetry. It uses the `registerOtel` function from Medusa, which accepts [OpenTelemetry configurations](https://open-telemetry.github.io/opentelemetry-js/interfaces/_opentelemetry_sdk-node.NodeSDKConfiguration.html) with the following custom Medusa options:
152
153 - `serviceName`: The name of your service, which you set to "medusa". You can change it to a more descriptive name if needed.
154 - `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 to `true`.
155
156 You can add any additional configurations to either Sentry or OpenTelemetry as needed for your use case.
157
158 ### c. Set Up a Sentry Project
159
160 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.
161
162 To set up a Sentry project:
163
164 1. [Log in or sign up](https://sentry.io/signup/) to Sentry.
165 2. 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.
166 3. In the "Select Platform" step, select "Node.js" as the platform, then select "Node, Vanilla" in the pop-up.
167
168 ![Screenshot of the pop up with Node, Vanilla selected](https://res.cloudinary.com/dza7lstvk/image/upload/v1750064385/Medusa%20Resources/CleanShot_2025-06-16_at_10.29.29_2x_dkmwtn.png)
169
170 4. 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.
171
172 ![Screenshot of the Configure Node.js SDK step with the DSN highlighted](https://res.cloudinary.com/dza7lstvk/image/upload/v1750064502/Medusa%20Resources/CleanShot_2025-06-16_at_12.00.36_2x_wlc0o1.png)
173
174 You can skip onboarding or the next steps for now. You'll test out the integration in the next step.
175
176 Then, add the following environment variable to your `.env` file in your Medusa application:
177
178 ```shell title=".env"
179 SENTRY_DSN=your_sentry_dsn_here
180 ```
181
182 Replace `your_sentry_dsn_here` with the DSN you copied from Sentry.
183
184 ### Test Tracing in Sentry
185
186 You can now test the integration to ensure operations are traced in Sentry.
187
188 First, start your Medusa application by running the following command in your `apps/backend` directory:
189
190 ```bash npm2yarn
191 npm run dev
192 ```
193
194 You'll find in the terminal the following message:
195
196 ```bash
197 info: OTEL registered
198 ```
199 This message indicates that OpenTelemetry has been successfully registered and instrumentation is set up successfully.
200
201 Then, open your Medusa Admin dashboard in your browser at `http://localhost:9000/app` and log in with the user you created earlier.
202
203 You can already find the database, workflow executions, and HTTP requests traced in your Sentry project:
204
205 1. In your Sentry dashboard, go to Explore → Traces from the sidebar.
206 2. You'll find a list of traces on this page, including HTTP requests made to log in to the Medusa Admin dashboard.
207
208 ![Sentry dashboard with traces listed](https://res.cloudinary.com/dza7lstvk/image/upload/v1750065824/Medusa%20Resources/CleanShot_2025-06-16_at_12.23.29_2x_at87kq.png)
209
210 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.
211
212 ![Sentry trace details with HTTP request and workflow execution](https://res.cloudinary.com/dza7lstvk/image/upload/v1750065922/Medusa%20Resources/CleanShot_2025-06-16_at_12.25.10_2x_w8jzgl.png)
213
214 ### Test Tracing for Customizations
215
216 Tracing also works for your custom API routes, workflow executions, Query usages, and database operations.
217
218 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.
219
220 <Note title="Tip">
221
222 An [API Route](!docs!/learn/fundamentals/api-routes) is an endpoint that exposes commerce features to external applications and clients, such as storefronts.
223
224 </Note>
225
226 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`.
227
228 So, to create an API route at the path `/test-sentry`, create the file `src/api/test-sentry/route.ts` with the following content:
229
230 ```ts title="src/api/test-sentry/route.ts"
231 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
232 import { MedusaError } from "@medusajs/framework/utils"
233
234 export async function GET(
235 req: MedusaRequest,
236 res: MedusaResponse
237 ) {
238 throw new MedusaError(
239 MedusaError.Types.UNEXPECTED_STATE,
240 "This is a test error for Sentry integration."
241 )
242 }
243 ```
244
245 Since you export a `GET` route handler function, you expose a `GET` API route at `/test-sentry`. The route handler function accepts two parameters:
246
247 1. A request object with details and context on the request, such as body parameters.
248 2. A response object to manipulate and send the response.
249
250 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.
251
252 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`:
253
254 ```bash
255 curl http://localhost:9000/test-sentry
256 ```
257
258 You'll receive the following error in the response:
259
260 ```json
261 {
262 "type": "unexpected_state",
263 "message": "This is a test error for Sentry integration."
264 }
265 ```
266
267 If you refresh the Tracing page in your Sentry dashboard, you should see a new trace for the `/test-sentry` API route.
268
269 <Note>
270
271 It may take a few seconds for the trace to appear in Sentry, so if you don't see it immediately, wait a bit and refresh the page.
272
273 </Note>
274
275 ![Trace dashboard with the test API route trace](https://res.cloudinary.com/dza7lstvk/image/upload/v1750066376/Medusa%20Resources/CleanShot_2025-06-16_at_12.32.37_2x_uox6r1.png)
276
277 If you click on the Trace ID, you'll see the details of the trace.
278
279 ![Sentry trace details with error breadcrumbs](https://res.cloudinary.com/dza7lstvk/image/upload/v1750066493/Medusa%20Resources/CleanShot_2025-06-16_at_12.34.33_2x_unzktq.png)
280
281 ---
282
283 ## Step 3: Capture HTTP Request Errors in Sentry
284
285 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.
286
287 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.
288
289 <Note>
290
291 Refer to the [Throwing and Handling Errors](!docs!/learn/fundamentals/api-routes/errors) guide to learn more about Medusa's default error handling behavior.
292
293 </Note>
294
295 To customize the error handler, create the file `src/api/middlewares.ts` with the following content:
296
297 export const errorHandlerHighlights = [
298 ["20", "captureException", "Capture the error in Sentry."],
299 ["21", "originalErrorHandler", "Call Medusa's default error handler."],
300 ]
301
302 ```ts title="src/api/middlewares.ts" highlights={errorHandlerHighlights}
303 import {
304 defineMiddlewares,
305 errorHandler,
306 MedusaNextFunction,
307 MedusaRequest,
308 MedusaResponse,
309 } from "@medusajs/framework/http"
310 import { MedusaError } from "@medusajs/framework/utils"
311 import * as Sentry from "@sentry/node"
312
313 const originalErrorHandler = errorHandler()
314
315 export default defineMiddlewares({
316 errorHandler: (
317 error: MedusaError | any,
318 req: MedusaRequest,
319 res: MedusaResponse,
320 next: MedusaNextFunction
321 ) => {
322 Sentry.captureException(error)
323 return originalErrorHandler(error, req, res, next)
324 },
325 })
326 ```
327
328 You export the `defineMiddlewares` function that allows you to apply middlewares and customize Medusa's default error handler.
329
330 The function accepts an object with the `errorHandler` property, whose value is a custom function that handles errors thrown in API routes.
331
332 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.
333
334 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.
335
336 ### Test Error Capturing in Sentry
337
338 To test out error capturing in Sentry, start the Medusa application if it's not already running:
339
340 ```bash npm2yarn
341 npm run dev
342 ```
343
344 Then, send a `GET` request to the `/test-sentry` API route you created earlier:
345
346 ```bash
347 curl http://localhost:9000/test-sentry
348 ```
349
350 You'll receive the same error response as before:
351
352 ```json
353 {
354 "type": "unexpected_state",
355 "message": "This is a test error for Sentry integration."
356 }
357 ```
358
359 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.
360
361 You'll find in the tracing page the thrown error highlighted in red, indicating that it was captured by Sentry.
362
363 ![Sentry trace details with error message](https://res.cloudinary.com/dza7lstvk/image/upload/v1750347022/Medusa%20Resources/CleanShot_2025-06-19_at_18.29.57_2x_aenvrd.png)
364
365 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.
366
367 ![Error details in Sentry](https://res.cloudinary.com/dza7lstvk/image/upload/v1750347022/Medusa%20Resources/CleanShot_2025-06-19_at_18.30.07_2x_oz5y9e.png)
368
369 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.
370
371 ---
372
373 ## Next Steps
374
375 You've now integrated Sentry with your Medusa application. You can continue using Sentry to monitor your application's performance and track errors.
376
377 You can also expand on your Sentry integration by enabling more features, such as:
378
379 - [Alerts](https://docs.sentry.io/product/alerts/) to get notified about critical issues in your application. You can receive alerts via email, Slack, or other channels.
380 - [Profiling](https://docs.sentry.io/platforms/javascript/guides/nextjs/profiling/node/) to analyze your application's performance and identify bottlenecks.
381 - [User feedback](https://docs.sentry.io/product/user-feedback/) to collect feedback in your frontend from users about their experience with your application.
382
383 If you're new to Medusa, check out the [main documentation](!docs!/learn), where you'll get a more in-depth understanding of all the concepts you've used in this guide and more.
384
385 To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx).
386
387 ### Troubleshooting
388
389 If you encounter issues during your development, check out the [troubleshooting guides](../../../troubleshooting/page.mdx).
390
391 ### Getting Help
392
393 If you encounter issues not covered in the troubleshooting guides:
394
395 1. Visit the [Medusa GitHub repository](https://github.com/medusajs/medusa) to report issues or ask questions.
396 2. Join the [Medusa Discord community](https://discord.gg/medusajs) for real-time support from community members.
397 3. Contact the [sales team](https://medusajs.com/contact/) to get help from the Medusa team.