Identify Individual Requests in ExpressJS

Learn how to debug user errors more easily by tagging each request.

Identify Individual Requests in ExpressJS
Photo by Noah Näf / Unsplash

When a user complains about a bug they encountered, you look in your server logs to try to find the cause.

But what if you have thousands of users at the same time. You can ask the user for the specific time when they encountered the error so that you can filter your logs accordingly. Most of the time, they don't remember the exact time, and it's unrealistic to expect them to keep track of such information.

What if you had a way to identify each unique request made to your server?


You'll use the uuid package to tag each request individually.

npm i uuid

All you have to do is create a middleware:

function addRequestId(req, res, next) {
  req.requestId = uuidv4();


This will add a property requestId to each request.

Then, you'll use a custom error handler to add this id to the response header so that clients can use it when reporting errors.

function errorHandler(err, req, res, next) {
  res.set('X-Request-Id', req.requestId);
  console.err(`Request Id: ${req.requestID}\n\n${err.stack}`)
  res.status(500).send("Server error");


Now you can simply access this header in your client side Javascript, and show it to users on the error page.

When users report the error, they'll mention this id, and you'll use it to filter your logs to find information about the error you logged from your handler for this particular request.