šŸš€ LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
šŸŽ“ COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
HTML MASTER CLASS /// LEARN TAGS /// BUILD STRUCTURE /// SEMANTIC WEB /// HTML MASTER CLASS /// LEARN TAGS ///

Untitled Lesson

⚔ Total XP: 0|šŸ’» backend XP: 0

Skill Matrix

UNLOCK NODES BY LEARNING NEW TAGS.

Select an unlocked node to view details root

Pascual Vila

Pascual Vila

Frontend Instructor // Code Syllabus

Common Pitfalls & Errors

The Error //

Forgetting to call next() (or send a response) inside a middleware function

// Wrong: request hangs forever const logger = (req, res, next) => { console.log(req.url); // missing next()! }; // Correct const logger = (req, res, next) => { console.log(req.url); next(); };

The Solution //

If a middleware neither calls next() nor sends a response with res.send()/res.json()/res.end(), Express has no instruction to move forward, and the client's request hangs until it eventually times out. Every code path in a middleware must either terminate the response or call next() — including inside if/else branches and catch blocks.

The Error //

Calling next() after already sending a response ("Cannot set headers after they are sent")

// Wrong: sends a response, then falls through to next() const requireAuth = (req, res, next) => { if (!req.user) { res.status(401).json({ error: 'Unauthorized' }); } next(); // still runs even after the response was sent! }; // Correct: return stops execution here const requireAuth = (req, res, next) => { if (!req.user) { return res.status(401).json({ error: 'Unauthorized' }); } next(); };

The Solution //

If a middleware calls res.send() or res.json() and then also calls next() (or calls next() twice), the request continues down the pipeline and a later handler tries to write to a response that's already closed, throwing the ERR_HTTP_HEADERS_SENT error. Always `return` immediately after sending a response so the function exits before reaching any subsequent next() call.

Continue Learning