HTTP 502 Bad Gateway — Causes, Fix & nginx Troubleshooting
The server, acting as a gateway or proxy, received an invalid response from an upstream server. The server is working but something upstream (backend service, database, API) is returning garbage or nothing.
When to Return 502
Typically generated by nginx, load balancers, or CDNs when your application server crashes or returns an unreadable response. Return 502 from application code when a downstream service responds with an invalid payload.
Common Causes
- Application server crashed or is not running
- nginx upstream connect failure
- Backend service returning invalid HTTP
- Upstream service returning 5xx but the proxy can't relay it
- Memory limit reached and process killed (OOM)
HTTP Response Example
HTTP/1.1 502 Bad Gateway
Content-Type: application/json
{"error": "Bad Gateway", "message": "Upstream service unreachable"}Code Examples
Express.js
// When calling an upstream service, return 502 if it's invalid
app.get('/proxy/data', async (req, res) => {
try {
const response = await fetch('https://upstream-service/data')
if (!response.ok) {
return res.status(502).json({
error: 'Bad Gateway',
message: 'Upstream service returned an error',
upstream: response.status,
})
}
const data = await response.json()
res.json(data)
} catch {
res.status(502).json({ error: 'Bad Gateway', message: 'Upstream service unreachable' })
}
})Next.js App Router
// Typically comes from your hosting provider (Vercel, etc.)
// when your Next.js serverless function crashes.
// For custom proxy routes:
export async function GET() {
try {
const res = await fetch(process.env.UPSTREAM_API!)
if (!res.ok) return Response.json({ error: 'Bad Gateway' }, { status: 502 })
return Response.json(await res.json())
} catch {
return Response.json({ error: 'Bad Gateway' }, { status: 502 })
}
}Related Status Codes
Frequently Asked Questions
What does HTTP 502 Bad Gateway mean?
The server, acting as a gateway or proxy, received an invalid response from an upstream server. The server is working but something upstream (backend service, database, API) is returning garbage or nothing.
When should an API return 502?
Typically generated by nginx, load balancers, or CDNs when your application server crashes or returns an unreadable response. Return 502 from application code when a downstream service responds with an invalid payload.
What causes an HTTP 502 error?
Common causes: Application server crashed or is not running; nginx upstream connect failure; Backend service returning invalid HTTP; Upstream service returning 5xx but the proxy can't relay it; Memory limit reached and process killed (OOM).
