Have you ever encountered a 504 Gateway Timeout from your AWS Application Load Balancer (ALB) when proxying requests via Axios, even though everything looks right on the surface?
Here’s a tricky issue I ran into — and how to avoid it in the future.
💥 The Setup
You're using AWS Lambda using a Node.js proxy to forward a POST
request to a backend behind ALB:
await axios.post('http://my-backend', {
timestamp: '2025-06-10 10:49:46',
token: 'fEjck23HJkLlrRkDKtNWVI:APA91bHphS5as...'
}, {
headers: {
'Content-Type': <keep it from original request>,
'Content-Length': <get from original request>
}
});
Looks harmless, but suddenly:
504 Gateway Timeout from ALB
And the backend logs show:
SyntaxError: Unterminated string in JSON at position xxx
🧠 Root Cause
The error comes from a mismatch between the Content-Length and the actual body size.
What actually happens:
- Axios serializes the data object to JSON.
- You manually set Content-Length: xxx or forward it from orignial request, but the serialized body is longer.
- The backend receives only the first xxx bytes.
- It tries to parse, but the JSON is incomplete.
- It waits for the rest of the body, but it never comes.
- Eventually, the connection times out → ALB returns a 504.
❌ Why Not a 400?
- Normally, a malformed JSON gives a 400 Bad Request.
- But here:
- The backend doesn't know the full body has been sent.
- It thinks the rest is still coming.
- So it never sends a response → ALB gives up and returns 504.
✅ The Fix
- Just don’t manually set Content-Length. Let Axios compute it.
await axios.post('http://my-backend', {
timestamp: '2025-06-10 10:49:46',
token: 'fEjck23HJkLlrRkDKtNWVI:APA91b...'
}, {
headers: {
'Content-Type': <keep it from original request>
// ✅ Do not manually set Content-Length
}
});
Axios will:
- Serialize the object to JSON
- Compute the correct length
- Set the header automatically
Have fun coding!
Top comments (0)