Real-world engineering is 20% writing new code and 80% reading, debugging, and optimizing existing systems. In this interactive lab, you will analyze broken code snippets representing real production defects and learn how to fix them.
Symptom: Clients send a GET request to /api/user, but the browser loader spins indefinitely until a 504 Gateway Timeout occurs.
// BROKEN CODE:
app.get('/api/user', async (req, res, next) => {
try {
const user = await User.findById(req.query.id);
if (!user) {
res.status(404); // BUG: Forgot .json() or .send()! Connection hangs!
return;
}
res.json(user);
} catch (err) {
// BUG: Caught error but forgot to call next(err) or send a 500!
}
});
// CORRECTED FIX:
app.get('/api/user', async (req, res, next) => {
try {
const user = await User.findById(req.query.id);
if (!user) {
return res.status(404).json({ error: 'User not found' }); // Fixed!
}
res.status(200).json(user);
} catch (err) {
next(err); // Fixed: Forward error to global error handler!
}
});
Symptom: Whenever one user triggers an export, all other users' web requests are completely blocked for 15 seconds.
// BROKEN CODE:
app.get('/api/export-data', (req, res) => {
// Synchronous JSON parsing of a 400MB string on the main thread!
const hugeData = fs.readFileSync('huge-dataset.json', 'utf8'); // Blocks!
const parsed = JSON.parse(hugeData); // Blocks!
res.json({ count: parsed.length });
});
// CORRECTED FIX: Use Streams or Worker Threads!
const { Worker } = require('worker_threads');
app.get('/api/export-data', (req, res, next) => {
const worker = new Worker('./workers/parseWorker.js', {
workerData: { filePath: 'huge-dataset.json' }
});
worker.on('message', (data) => res.json(data));
worker.on('error', next);
});
Boost your server-side JavaScript proficiency by studying these closely connected core modules:
Tools to diagnose memory leaks and event loop lag.
Best practices for writing bug-free code.
Reference working code implementations.