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.
