Add the Sentry SDK to Your Backend Project
Learn how to add the Sentry SDK to your backend codebase.
Step 3 of 5
This section walks you through how to import the sample app into your local dev environment, then add and initialize the Sentry SDK. If you're using your own source code, you can skip this section. Instead:
- Select your platform and follow its Getting Started guide to add the Sentry SDK to your code.
- Then, skip to the next step.
The sample app is a backend API built with Express and Node, using ECMAScript Modules (ESM).
Fork the sample application's repository on GitHub.
Clone the forked repository to your local environment:
If you have SSH set up:
Copiedgit clone git@github.com:<your_username>/tracing-tutorial-backend.gitgit clone git@github.com:<your_username>/tracing-tutorial-backend.gitOtherwise:
Copiedgit clone https://github.com/<your_username>/tracing-tutorial-backend.gitgit clone https://github.com/<your_username>/tracing-tutorial-backend.gitOpen the
tracing-tutorial-backendproject in your preferred code editor.
Sentry captures data by using a platform-specific SDK that you add to your app's runtime. To use the SDK, import and configure it in your source code. This demo project uses Sentry's Node SDK.
Navigate to the
tracing-tutorial-backendproject folder and install the Sentry Node SDK.Copiednpm install --save @sentry/nodenpm install --save @sentry/nodeyarn add @sentry/nodepnpm add @sentry/nodeCreate a file at the root level of your project and call it
instrument.js. Import and initialize the SDK using the following code:instrument.jsCopiedimport * as Sentry from "@sentry/node"; Sentry.init({ dsn: "<your_DSN_key>", // Capture 100% of transactions for tracing. tracesSampleRate: 1.0, });import * as Sentry from "@sentry/node"; Sentry.init({ dsn: "<your_DSN_key>", // Capture 100% of transactions for tracing. tracesSampleRate: 1.0, });It's important to import and initialize the SDK as early as possible in your application's lifecycle so Sentry can capture errors throughout it.
Add your DSN key to the Sentry SDK configuration.
Replace
<your_DSN_key>in the code above with the DSN key value you copied from the backend project you created in the previous section. This DSN should be different from the one you used on your frontend project — each project has its own unique DSN.Save the file.
The options set in
Sentry.init()are called the SDK's configuration. The only required option is the DSN; the SDK supports many others, which you can read about in our Configuration docs. The configuration above enables Sentry's error monitoring and Tracing features.Open your
server.jsfile, importSentry, and set up the error handler after all controllers and before any other error middleware. You don't importinstrument.jshere — you'll load it with Node's--importflag when you start the app (in the next step):
server.js+ import * as Sentry from "@sentry/node";
import express from "express";
import cors from "cors";
import productsRoute from "./routes/products.js";
const app = express();
app.use(express.static("public"));
app.use(cors());
app.get("/", (req, res) => {
res.send("<h1>Hello, Express.js Server here!</h1>");
});
app.get("/products/debug-sentry", (req, res) => {
console.log("Sentry Error thrown!");
throw new Error("My first Sentry error!");
});
app.use("/products", productsRoute);
+ // The error handler must be registered before any other error middleware and after all controllers.
+ Sentry.setupExpressErrorHandler(app);
+ // Optional fallthrough error handler
+ app.use(function onError(err, req, res, next) {
+ // The error id is attached to `res.sentry` to be returned
+ // and optionally displayed to the user for support.
+ console.log("500 error thrown!");
+ res.statusCode = 500;
+ res.end(res.sentry + "\n");
+ });
const port = 3001;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
+ import * as Sentry from "@sentry/node";
import express from "express";
import cors from "cors";
import productsRoute from "./routes/products.js";
const app = express();
app.use(express.static("public"));
app.use(cors());
app.get("/", (req, res) => {
res.send("<h1>Hello, Express.js Server here!</h1>");
});
app.get("/products/debug-sentry", (req, res) => {
console.log("Sentry Error thrown!");
throw new Error("My first Sentry error!");
});
app.use("/products", productsRoute);
+ // The error handler must be registered before any other error middleware and after all controllers.
+ Sentry.setupExpressErrorHandler(app);
+ // Optional fallthrough error handler
+ app.use(function onError(err, req, res, next) {
+ // The error id is attached to `res.sentry` to be returned
+ // and optionally displayed to the user for support.
+ console.log("500 error thrown!");
+ res.statusCode = 500;
+ res.end(res.sentry + "\n");
+ });
const port = 3001;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
In the tracing-tutorial-backend project folder:
Install project dependencies.
Copiednpm installnpm installyarnpnpm installStart the application:
Copiednpm startnpm startyarn startpnpm startThe sample app's
startscript runsnode --import ./instrument.js server.js. The--importflag runsinstrument.js(yourSentry.init()call) before the rest of the app loads — which is required for Sentry to instrument an ESM app correctly. If you adapt this to your own ESM project, start it the same way.Once the application starts, you'll see a confirmation message similar to this one in your terminal:
CopiedServer is running on port 3001Server is running on port 3001Troubleshooting tip: If the application fails to start due to syntax errors or errors for missing dependencies/modules, make sure you're using Node 18+ and install dependencies again.
Open the sample application in your browser.
The sample app should be running at http://localhost:3001/ or the URL output in your terminal in the last step. You should see the "Hello, Express.js Server here!" message.
Well done! You now have a sample Express backend app running with the Sentry SDK initialized. Next, Capture Your First Distributed Tracing Error to start using Sentry's distributed tracing.
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").