Error: Cannot Set Headers After They Are Sent to the Client
Error: Cannot Set Headers After They Are Sent to the Client If you've built APIs with Express for any length of time, you've probably seen this error: Error [ ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client Or: Cannot set headers after they are sent to the client The frustrating part is that the application often works for some requests and fails only under specific conditions. This error is almost always caused by sending multiple responses for the same request. Let's break down why it happens and how to prevent it in production code. Problem Consider this Express route: app . get ( " /users/:id " , ( req , res ) => { if ( ! req . params . id ) { res . status ( 400 ). json ({ error : " User ID required " }); } res . json ({ id : req . params . id }); }); Looks harmless. But if the first response is sent, Express continues executing the remaining code. Result: Error [ ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client The server attempts to send two responses for a single request. HTTP doesn't allow that. Why It Happens A request can only receive one response. Once Express sends: res . send (); or res . json (); or res . redirect (); or res . end (); the HTTP headers are already transmitted. Any attempt to modify headers or send another response will trigger the error. In production systems, this usually happens because of: Missing return statements Multiple async operations Duplicate error handling Middleware issues Promise and callback mixing Race conditions Example Missing Return Statement This is the most common cause. app . get ( " /profile " , ( req , res ) => { if ( ! req . user ) { res . status ( 401 ). json ({ error : " Unauthorized " }); } res . json ( req . user ); }); If req.user is missing: res . status ( 401 ). json (...) runs first. Then: res . json ( req . user ) runs immediately afterward. Two responses. One request. Crash. Correct Version app . get ( " /profile " , ( req , res ) => { if ( ! req