All guides
Errors and events·3 min read

SEND EVENTS FROM NODE.JS

Report errors and events from a Node.js app or script.

1

Add a small helper

Node.js 18 and newer have fetch built in, so there's nothing to install:

const PUSH_URL = process.env.UPGURU_PUSH_URL;

export async function report(level, message, context = {}) {
  try {
    await fetch(PUSH_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ level, message, context }),
    });
  } catch {
    // Never let monitoring break your app.
  }
}
2

Send events and errors

await report("info", "Order placed", { orderId: 1042 });

try {
  await chargeCustomer(order);
} catch (err) {
  await report("error", err.message, {
    exception: { class: err.name, message: err.message, trace: err.stack },
  });
  throw err;
}
3

Catch everything else

In an Express app, add this after your routes; for any app, also report crashes:

app.use((err, req, res, next) => {
  report("error", err.message, {
    url: req.originalUrl,
    exception: { class: err.name, message: err.message, trace: err.stack },
  });
  next(err);
});

process.on("unhandledRejection", (reason) => report("error", String(reason)));
Keep the push URL in an environment variable (UPGURU_PUSH_URL) rather than in your code.