Example HTTP Response
HTTP/1.1 502 Bad Gateway
Content-Type: text/html
<h1>Bad Gateway</h1>- Upstream server is down
- Proxy received invalid response
- Backend server crashed
What does this mean?
Lost in translation! The middleman server got gibberish from the backend. Like a game of telephone gone wrong.
Technical Definition
The server was acting as a gateway and received an invalid response from the upstream server.
RFC Says
"The 502 (Bad Gateway) status code indicates that the server, while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request."
Plain English:
502 means 'I'm a proxy/gateway, and the server behind me sent back a response I couldn't understand or process.' This is common when a reverse proxy (like nginx or a load balancer) can't communicate properly with your application server - maybe your app crashed, returned invalid HTTP, or the connection broke.
Common Misinterpretation
Don't return 502 from your application code for downstream API failures - use 500 or 503 instead. 502 should come from infrastructure layer (reverse proxies, load balancers, API gateways) when they can't get a valid response from your app.
Ready-to-use code for returning this HTTP status in your application:
// Express.js
app.get('/example', (req, res) => {
res.status(502).json({
error: 'Bad Gateway',
message: 'Your error message here'
});
});
// Native HTTP
const http = require('http');
http.createServer((req, res) => {
res.writeHead(502, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
error: 'Bad Gateway',
message: 'Your error message here'
}));
}).listen(3000);- Proxy/gateway received invalid response from upstream server
- Backend server returned malformed data or crashed mid-response
- Use when your server is a proxy and upstream failed
- Use 504 if the issue is timeout rather than bad response