In this guide
A simple guide to this issue: 'Cannot set headers after they are sent to the client' in Express. Learn why it happens, what to check first, and how to fix it.
This error means your route handler called res.send/res.json/res.redirect more than once for a single request. An HTTP response can only be sent once. The fix is to make sure every path ends in exactly one response.
The Error
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
Cause 1: Missing return After res.send
// ❌ Both blocks can run
app.get("/user", (req, res) => {
if (!req.user) res.status(401).json({ error: "Unauthorized" });
res.json(req.user); // runs even after the 401 above
});
// ✅ Return to stop execution
app.get("/user", (req, res) => {
if (!req.user) return res.status(401).json({ error: "Unauthorized" });
return res.json(req.user);
});Cause 2: Responding in a Loop or Callback
Calling res.send inside a forEach or multiple async callbacks fires it repeatedly. Collect results first, then respond once after the loop.
Cause 3: Responding Then Continuing Async Work
// ✅ One response, guarded by try/catch
app.post("/save", async (req, res) => {
try {
const doc = await save(req.body);
return res.status(201).json(doc);
} catch (err) {
return res.status(500).json({ error: err.message });
}
});Rule of Thumb
Always return your response calls. It turns 'maybe two responses' into a compile-time-obvious single exit point.
Relevant Scaleup Infotech Services
Keep Reading
Fix React Search Results Showing the Wrong Data
Fix React search race conditions with request cleanup, cancellation, and stale-response checks. Includes code and a slow-network verification checklist.
5 min readFix Next.js Environment Variables Missing in Production
Fix missing Next.js production environment variables by checking build-time values, public prefixes, deployment settings, and the exact release artifact.
5 min readFix Laravel Queue Jobs Not Processing After Deployment
Recover Laravel queue jobs after deployment by checking the connection, queue name, workers, cached configuration, failed jobs, and restart behavior.
5 min read