{"success":true,"name":"in-express-send-exactly-one-response-per-request-and-return-","description":"Using Express and hitting 'headers already sent' errors or double responses","category":"ai-brimind","path":"ai-brimind/in-express-send-exactly-one-response-per-request-and-return-/SKILL.md","file":"SKILL.md","content":"---\nname: in-express-send-exactly-one-response-per-request-and-return-\ndescription: \"Using Express and hitting 'headers already sent' errors or double responses\"\n---\n\n# In Express, Send Exactly One Response Per Request — and return After You Send It\n\n## When to use\nProject uses Express/Node, and handlers can reach two response calls on one request, or crash logs show 'Cannot set headers after they are sent'.\n\n## Example request\nvalidation fails, res.status(400).json(...) runs — but no return → execution continues into the success res.json below; two answers, one question. error caught and responded, then the finally block responds again → the second send crashes; duplicate reply. an if-branch sends, the code after the if also sends → works until that branch is taken; latent double-send. — each forgot that sending a response doesn't stop the function.\n\n## Instructions\nAct as a telephone operator who knows that answering a call doesn't hang up the line — the conversation continues until YOU end it. In Express, res.json and res.send transmit the response but do NOT stop your handler: every line after them still executes, and if any of it sends again, you get the infamous 'Cannot set headers after they are sent' crash — or worse, subtle corruption when the second send half-fails. The discipline is mechanical: treat every response call as the handler's exit and enforce it with return — 'return res.status(400).json(...)' — so early exits (validation failures, permission denials, not-found cases per the guard-clause rules) genuinely exit; audit each handler by tracing every path and confirming it crosses exactly ONE send. The async variant is nastier: a response sent inside a callback or after an await, racing code below it — structure handlers so the send is the final act of each path, per the async rules. Know the middleware angle: after sending, never call next() expecting more processing, and in error middleware, check whether headers were already sent (the headersSent flag) and delegate to the default handler if so — the pattern Express's own docs prescribe. When the crash appears, don't hunt where it threw — hunt the FIRST send on that request's path; the error names the second offender, but the bug is usually a missing return above it. Only proceed once every handler path provably sends once and stops.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #824\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}