Error Handling and Logging in Express: Winston, Morgan and Request IDs

Node.js and Express: Build a Back End API from Scratch · Architecture, Reliability and Performance · 7 min read · Updated

Same error, two stories

  1. A route throws, either on purpose with an AppError or by accident with a bug.
  2. In Express 5 even a rejected async function reaches the same error handler.
  3. The client receives a short, safe message and the request id.
  4. The developer log receives the stack, the request id and the context, as JSON.

When something goes wrong in production, you cannot sit beside the server and watch. You have two sources of truth: the reply that the client received and the logs that your server wrote. If the reply leaks a stack trace, you have given attackers a map. If the logs are missing, you cannot find the cause. This lesson builds a small but complete system that gets both right.

Two audiences, two messages

Every error has two readers. The client needs to know what it can fix: "Item not found", "Email is invalid". The developer needs everything: the full message, the stack trace, the user and the request. The rule is simple: show client errors (status 400 to 499) to the client, and hide the details of server errors (500 and above), while writing them in full to the log. The custom AppError class carries a status code, a short code and a flag expose that says whether its message is safe to send.

import express from 'express';
import morgan from 'morgan';
import winston from 'winston';
import crypto from 'node:crypto';

// Custom error classes carry an HTTP status and a safe message for the client.
export class AppError extends Error {
  constructor(message, status = 500, code = 'INTERNAL') {
    super(message);
    this.status = status;
    this.code = code;
    this.expose = status < 500;     // only show messages of client errors, never of server bugs
  }
}
export const notFound = (what) => new AppError(`${what} not found`, 404, 'NOT_FOUND');
export const badRequest = (message) => new AppError(message, 400, 'BAD_REQUEST');

// Winston: levels, structured JSON, and one place to choose where logs go.
export function createLogger({ silent = false, stream } = {}) {
  return winston.createLogger({
    level: process.env.LOG_LEVEL ?? 'info',
    silent,
    format: winston.format.combine(winston.format.timestamp(), winston.format.errors({ stack: true }), winston.format.json()),
    transports: [stream ? new winston.transports.Stream({ stream }) : new winston.transports.Console()],
  });
}

export function createApp({ logger = createLogger({ silent: true }) } = {}) {
  const app = express();

  // Every request gets an id, so you can find all log lines of one request.
  app.use((req, res, next) => { req.id = req.get('x-request-id') ?? crypto.randomUUID(); res.set('x-request-id', req.id); next(); });

  // Morgan writes one line per request. We send it into Winston so all logs go to one place.
  morgan.token('id', (req) => req.id);
  app.use(morgan(':id :method :url :status :response-time ms', { stream: { write: (line) => logger.info(line.trim()) } }));

  app.get('/items/:id', (req, res) => {
    if (req.params.id !== '1') throw notFound('Item');
    res.json({ id: 1 });
  });
  app.get('/boom', () => { throw new Error('database password is hunter2'); });   // a bug with a secret in its message

  app.use((req, res) => res.status(404).json({ error: 'Not found', requestId: req.id }));

  // The ONE error handler. Express 5 also sends rejected promises from async handlers here.
  app.use((err, req, res, next) => {
    const status = err.status ?? 500;
    logger[status >= 500 ? 'error' : 'warn']({ message: err.message, code: err.code, status, requestId: req.id, stack: status >= 500 ? err.stack : undefined });
    res.status(status).json({ error: err.expose ? err.message : 'Something went wrong', code: err.code ?? 'INTERNAL', requestId: req.id });
  });
  return app;
}

Read the code from the top. AppError and its helpers notFound and badRequest are the errors that your own code throws on purpose. The error handler at the end decides: if the error is an AppError with a status below 500, send its message and code. For anything else, such as a crash from a bug or a library, log the full error and send only Something went wrong. In Express 5, a rejected promise in an async handler goes to this handler automatically, so you no longer need to wrap every route in try/catch.

Winston: structured logs

console.log is fine on your laptop and poor in production. Winston is a logging library with levels (error, warn, info, debug), timestamps and several outputs, called transports, such as the console, files or a cloud service. The example writes JSON, one object per line, because tools like Datadog, Grafana Loki or the ELK stack can search and graph JSON easily. Set the level from an environment variable, LOG_LEVEL, so you can turn on debug for a short time without changing code.

Morgan and request ids

Morgan writes one line for each request: method, URL, status and the time taken. Here its output is sent *into* Winston, so every log line goes to the same place in the same format. Each request also receives a unique request id, taken from the incoming x-request-id header or generated, and returned in the response. When a user reports a problem, ask for that id, search the logs for it, and you will find every line that belongs to that one request.

  1. Make a folder and open it in a terminal. Run npm init -y, then open package.json and add "type": "module" so that import works.
  2. Install what the lesson needs: npm install express winston morgan.
  3. Save the code as errors.js. The test needs npm install -D supertest.
import test from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { PassThrough } from 'node:stream';
import { createApp, createLogger } from './ar34-errors-logs.js';

test('client errors show their message, server errors hide it but are logged', async () => {
  const stream = new PassThrough();
  let output = '';
  stream.on('data', (chunk) => { output += chunk; });
  const app = createApp({ logger: createLogger({ stream }) });

  const missing = await request(app).get('/items/9');
  assert.equal(missing.status, 404);
  assert.equal(missing.body.error, 'Item not found');
  assert.equal(missing.body.code, 'NOT_FOUND');

  const boom = await request(app).get('/boom').set('x-request-id', 'req-123');
  assert.equal(boom.status, 500);
  assert.equal(boom.body.error, 'Something went wrong');          // the secret is NOT sent to the client
  assert.equal(boom.body.requestId, 'req-123');

  await new Promise((resolve) => setTimeout(resolve, 20));
  const lines = output.trim().split('\n').map((l) => JSON.parse(l));
  const serverError = lines.find((l) => l.level === 'error');
  assert.match(serverError.message, /hunter2/);                    // ...but it IS in the log, with the request id
  assert.equal(serverError.requestId, 'req-123');
  assert.ok(lines.some((l) => l.level === 'info' && l.message.includes('req-123')));
});
ok 1 - client errors show their message, server errors hide it but are logged
  • Never log passwords, tokens, card numbers or full personal data. Remove them before logging.
  • Log at the right level: error for failures you must act on, warn for strange but survivable, info for normal events.
  • Watch the logs, or set up alerts. A log that nobody reads does not protect you.
  • Also handle the two global events, unhandledRejection and uncaughtException: log them and exit, and let your process manager restart the app, because the program may be in an unknown state.

Your task

  1. Add a ValidationError subclass with status 422 that carries a list of field messages.
  2. Log the user id in each request line when the user is logged in.
  3. Send the logs to a file as well, with a daily rotation package such as winston-daily-rotate-file.

How to check it worked

  • A thrown server bug shows only a safe message to the client but the stack in the log.
  • Every response has an x-request-id header.
  • You can say which status codes are safe to show messages for.

Frequently asked questions

Why hide the message of a 500 error?

It may contain file paths, query text or library details that help an attacker. Log it fully and show the client something generic.

Winston or console.log?

console.log is fine to learn. In production, Winston or a similar library gives levels, JSON and several outputs.

What is a request id for?

It lets you find all log lines of one request, and a user can quote it in a support message.

Practise with interview questions