Observability with Express and Busgnag - In a easy way
Tags: backend, observability, javascript, beginners
Published: 2024-02-19 22:23:29

This article must be one of your first steps into learning what observability tools does and how you can start using them. During this article, we will be implementing Bugsnag on a Node.Js + Express project.

[Check out the complete source code](https://github.com/igorfelipeduca/express-bugsnag)

- [What are middlewares](#what-are-middlewares)
- [Setting up the project](#setting-up-the-project)
- [Creating the middleware (Optional)](#creating-the-middleware-optional)
- [Testing the middleware (Optional)](#testing-the-middleware-optional)
- [Sending the errors to a observability tool (Bugsnag)](#sending-the-errors-to-a-observability-tool-bugsnag)
- [Final code](#final-code)
- [Testing how the logs work](#testing-how-the-logs-work)

## What are middlewares

Imagine that you want something to do something everytime your application receives a signal -- this signal can be a new request, an error, a subscription, a webhook, etc. -- in order to do some parsing with the received information... you are probably needing a new middleware for your application.


![Express middleware explained](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yv81g4xt7qj2rozl91bx.png)

A middleware's main function is to intercept new requests (or events) and run a callback function using the received parameters, so, this way, you can go and do something with that data.

## Setting up the project

Go ahead and install the base dependencies for a express application: 

```
npm install express body-parser cors
```

```js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");

const app = express();

app.use(bodyParser.json());
app.use(cors());

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
```

The code above is a base for you to start your new express server application with nodejs and javascript.

## Creating the middleware (Optional)

To create a middleware with express, you need to use the `.use()` method. This method will make sure that everything that happens in your application will be covered in that function (the middleware one).

```js
app.use((err, req, res, next) => {
    console.log("something broke");
});

// err -> If there is an error in the application, it will be stored on the err object.
// req -> The request object.
// res -> The response object.
// next -> The next middleware in the stack.
```

## Testing the middleware (Optional)

We have not set any routes, so, if you go ahead and create a fake route to throw errors no matter what:

```js
app.get("/", (req, res) => {
  throw new Error("something went wrong");
});
```

Now, if you go ahead and make a GET request with: 
```curl
curl http://localhost:3000
``` 
(or it could be using your Postman or other HTTP agent), you should see this error:

![Terminal showing the API expected error](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/agpiwz7dndiiub32vvyr.png)

## Sending the errors to a observability tool (Bugsnag)

First things first, you must go ahead and create an account at [Busgnag](https://www.bugsnag.com).

After creating your account, select Express as a technology for your project and you should see this example code:

![Example integration code at Bugsnag](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q1k2j45lrtan3w6ws8ae.png)

So, let us go ahead and follow those steps.

First, install bugsnag in your project

```
npm install @bugsnag/js @bugsnag/plugin-express --save
```

After installing bugsnag, replace the sample code in your project:

```js
const Bugsnag = require('@bugsnag/js')
const BugsnagPluginExpress = require('@bugsnag/plugin-express')

Bugsnag.start({
  apiKey: '<YOUR-API-KEY>',
  plugins: [BugsnagPluginExpress]
})
```

Bugsnag have their own middleware service that does a abstraction of express middleware (the one that we have created), so, let us go and replace ours with the one that Bugsnag provides.

```js
// This must be the first piece of middleware in the stack.
// It can only capture errors in downstream middleware
app.use(middleware.requestHandler)

/* all other middleware and application routes go here */

// This handles any errors that Express catches
app.use(middleware.errorHandler)
```

## Final code

```js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const Bugsnag = require("@bugsnag/js");
const BugsnagPluginExpress = require("@bugsnag/plugin-express");

Bugsnag.start({
  apiKey: '<YOUR-API-KEY>',
  plugins: [BugsnagPluginExpress],
});

const app = express();

app.use(bodyParser.json());
app.use(cors());

const PORT = process.env.PORT || 3000;

app.use(middleware.requestHandler);

app.get("/", (req, res) => {
  throw new Error("something went wrong");
});

app.use(middleware.errorHandler);

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
```
## Testing how the logs work

Now let us go and hit that error endpoint again with:
```curl
curl http://localhost:3000
``` 

If you have done all of the steps, in a minute or so you will be able to see data at your Bugsnag dashboard:


![Bugsnag dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/izbq0fae8dwujhery012.png)

And that's it! Now you are able to see all of your server errors at Bugsnag and have a pretty good free-tier observability tool. To know more about pricing features, check it out [here](https://www.bugsnag.com/pricing/).

------ 

Liked this article? Show some love in the comments and follow me at [Twitter](https://twitter.com/ducaswtf).

------

Photo by <a href="https://unsplash.com/@franku84?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Vadim Bogulov</a> on <a href="https://unsplash.com/photos/a-close-up-of-a-brown-and-black-surface-ibaDHUAVBug?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Unsplash</a>