Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

API Gateway returns 502 because the Lambda proxy response has the wrong format

Error502 Bad Gateway

Short answer

With a Lambda proxy integration, API Gateway only accepts a response object with statusCode, optional headers and a body string. Anything else, such as a bare string, a plain object or an array in headers, becomes a 502. Return the documented shape from an async handler. Callback handlers stop working from Node.js 24.

  • Applies to Node.js 22, Node.js 24, API Gateway REST API
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Call your handler locally with an empty event and look at what it returns. If the result has no statusCode, the cause is the first one below.

    node -e "import('./index.mjs').then(async m => console.log(JSON.stringify(await m.handler({}))))"
  2. 2Match what you see, then jump to its fix

    1. 1The local call prints a bare value, or an object with no statusCodeThe handler returns something other than the proxy response shapeFix
    2. 2The function returns an object, but the body field holds an object or the statusCode is quotedstatusCode is a string or body is an objectFix
    3. 3It worked on Node.js 22 and started failing after switching the runtime to nodejs24.xA callback handler on a runtime that no longer supports callbacksFix
    4. 4The 502 appears only on routes that set cookies or repeated headersA multi-value header is placed in headersFix
    5. 5The route returns images or files and the response is a 502 or unreadableA binary body is returned as it isFix

What does the error look like?

  • 502 Bad Gateway
  • 502 Bad Gateway from a Lambda proxy integration, while the function itself ran without an error

Cause 1 of 5

The handler returns something other than the proxy response shape

1Check

In proxy integration, API Gateway requires the function output in one fixed JSON format. Any other output makes it return a 502 Bad Gateway error.

grep -n "return" index.mjs

2Fix

Return an object with statusCode, optional headers, and a body. In an async Node.js handler a plain return is enough.

export const handler = async (event) => {
  return {
    statusCode: 200,
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ ok: true }),
  };
};

3Verify

The local call prints an object with statusCode, then the API URL answers 200.

curl -i https://abc123.execute-api.us-east-1.amazonaws.com/prod/items

Confirmed by docs.aws.amazon.com

Did this fix it?

Cause 2 of 5

statusCode is a string or body is an object

1Check

The documented output has statusCode as a number and body as a JSON string. A raw object in body, or a quoted status such as '200', does not match.

node -e "import('./index.mjs').then(async m => { const r = await m.handler({}); console.log(typeof r.statusCode, typeof r.body) })"

2Fix

Send statusCode as a number and turn the body into a string with JSON.stringify.

// wrong
return { statusCode: '200', body: { ok: true } };

// right
return { statusCode: 200, body: JSON.stringify({ ok: true }) };

3Verify

The check prints number and string, and the API answers 200.

curl -i https://abc123.execute-api.us-east-1.amazonaws.com/prod/items

Confirmed by docs.aws.amazon.com

Did this fix it?

Cause 3 of 5

A callback handler on a runtime that no longer supports callbacks

1Check

The Lambda docs say callback-based handlers are only supported up to Node.js 22. From Node.js 24 the handler must be async.

grep -n "callback" index.mjs

2Fix

Rewrite the handler as async and return the response instead of calling callback.

// before (Node.js 22 and older)
export const handler = (event, context, callback) => {
  callback(null, { statusCode: 200, body: 'results' });
};

// after
export const handler = async (event) => {
  return { statusCode: 200, body: 'results' };
};

3Verify

Invoke the API again and confirm the status is 200, not 502.

curl -i https://abc123.execute-api.us-east-1.amazonaws.com/prod/items

Confirmed by docs.aws.amazon.com

Did this fix it?

Cause 4 of 5

A multi-value header is placed in headers

1Check

The headers key can only hold single-value headers. A header with several values belongs in multiValueHeaders.

grep -n "headers" index.mjs

2Fix

Move headers that carry several values into multiValueHeaders, and keep the rest in headers.

return {
  statusCode: 200,
  headers: { 'Content-Type': 'application/json' },
  multiValueHeaders: { 'Set-Cookie': ['a=1; Path=/', 'b=2; Path=/'] },
  body: JSON.stringify({ ok: true }),
};

3Verify

Request the route and look for both Set-Cookie headers.

curl -si https://abc123.execute-api.us-east-1.amazonaws.com/prod/login | grep -i set-cookie

Confirmed by docs.aws.amazon.com

Did this fix it?

Cause 5 of 5

A binary body is returned as it is

1Check

A body that is a binary blob has to be a Base64 string with isBase64Encoded set to true, and the API needs */* as a Binary Media Type.

grep -n "isBase64Encoded" index.mjs

2Fix

Encode the bytes as Base64, set isBase64Encoded to true, and add */* as a Binary Media Type on the API.

return {
  statusCode: 200,
  headers: { 'Content-Type': 'image/png' },
  isBase64Encoded: true,
  body: buffer.toString('base64'),
};

3Verify

Download the route and open the file.

curl -s https://abc123.execute-api.us-east-1.amazonaws.com/prod/logo -o logo.png && file logo.png

Confirmed by docs.aws.amazon.com

Did this fix it?

How do I stop it coming back?

  • Write one helper that builds the response object and use it in every route.
  • Unit test the handler by checking that the result has a numeric statusCode and a string body.
  • Check the Lambda runtime version before a runtime upgrade, and look for callback handlers first.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Back end

ng serve says it cannot determine the project or target

Cannot determine project for command.

The Angular CLI looked through angular.json for a project that defines the target you asked for (serve, build, test) and found none, or found several and could not pick one.

3 causes, each with a fix

Back end

ng serve cannot find the dev-server builder package

Could not find the implementation for builder @angular/build:dev-server

The builder named in angular.json (for example @angular-devkit/build-angular:dev-server) is looked up as an npm package starting from the workspace root.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.