Debugging (Express)
Debugging an Express application means finding out why a route returns the wrong data, hangs, or crashes the server. Express offers built-in debug logging, Node has a full debugger you can attach from Chrome or VS Code, and small tools like request loggers and error-handling middleware make problems visible. Using these instead of scattering console.log everywhere saves a lot of time.
Turning on Express's own debug output
Express uses the debug package internally. Setting the DEBUG environment variable shows what Express is doing: which routes are registered, which middleware runs, and how each request is matched.
# macOS / Linux
DEBUG=express:* node index.js
# Windows PowerShell
$env:DEBUG = "express:*"; node index.js
# Your own namespaced logs (install with: npm install debug)
DEBUG=app:* node index.js
You can use the same package for your own logs. Create a logger with const log = require('debug')('app:db') and call log('connected'). The messages only appear when DEBUG includes that namespace, so you can leave them in the code without cluttering production output.
Using breakpoints with --inspect
Running node --inspect index.js starts the server with the inspector enabled. Open chrome://inspect in Chrome or use the "JavaScript Debug Terminal" in VS Code, and you can set breakpoints, step through a route handler line by line, and hover over variables like req.body to see their values. Use --inspect-brk to pause on the first line, which helps when the bug happens during startup. Adding the statement debugger; in your code pauses execution there whenever a debugger is attached.
Logging requests and catching errors in one place
Seeing every request with its status code and response time often reveals the problem immediately. The morgan middleware does this in one line. Pair it with an error-handling middleware so failures are logged consistently.
const express = require('express');
const morgan = require('morgan');
const app = express();
app.use(morgan('dev')); // GET /api/users 200 4.1 ms
app.use(express.json());
app.get('/api/users/:id', async (req, res, next) => {
try {
const user = await findUser(req.params.id);
if (!user) return res.status(404).json({ error: 'Not found' });
res.json(user);
} catch (err) {
next(err); // hand the error to Express
}
});
// Error handler: must have exactly four parameters
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong' });
});
app.listen(3000);
Express identifies error handlers by their four arguments, so keep next in the signature even if you do not use it, and register the handler after all your routes.
The bug that hides: async errors and hanging requests
In Express 4, an error thrown inside an async route handler is not caught by Express. The promise rejects, the error handler never runs, and the request just hangs until the browser times out. That is why the example wraps the work in try/catch and calls next(err). Express 5 forwards rejected promises automatically, but with Express 4 you must do it yourself or use a small wrapper helper.
A related symptom is the error "Cannot set headers after they are sent to the client". It means a handler sent a response and then kept running and tried to send another. Usually a return is missing before an early res.status(404).json(...).
A short checklist
- Request hangs: check that every code path sends a response or calls
next(). - Route not matched: run with
DEBUG=express:routerand compare paths and methods. req.bodyis undefined: confirmexpress.json()is registered before the route.- Unclear state: set a breakpoint with
--inspectand inspect the variables.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.