Getting 502 error when calling Lambda function through API Gateway from React app

I have a React application that makes POST requests to my AWS Lambda function through API Gateway. The setup should be straightforward but I keep getting a 502 Bad Gateway error.

My Lambda function processes data arrays and calls an external AI service. When I test it directly in the AWS console it works perfectly fine. But when my frontend tries to call it I get this error.

The CloudWatch logs show something about a missing log group which is confusing because the function itself runs fine during testing.

Here’s my frontend code that makes the request:

const apiData = [
  { name: "username", dataType: "text" },
  { name: "userAge", dataType: "number" }
];

const response = await fetch('https://myapi.execute-api.region.amazonaws.com/stage/process-data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ apiData })
});

I’ve set up CORS headers in my Lambda response like this:

const responseHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'POST, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type',
  'Content-Type': 'application/json'
};

The Lambda function uses an external API call with node-fetch and I deployed it as a zip file with the package.json included. What could be causing this 502 error when everything works fine in the console?

yeah, sounds like a timeout issue. lambda has a default of 3 secs, if the ai call takes longer, it’ll throw that 502 error. try increasing the timeout to 30 secs in the aws console, and check if api gateway settings align.

are you handling the OPTIONS preflight request? browsers send that before the actual POST, and if your lambda doesn’t respond to OPTIONS with proper CORS headers, you’ll get weird 502s. does your lambda check for event.httpMethod === 'OPTIONS' and return early with just the headers?

That 502 error with missing log messages means your Lambda is crashing before it can send a proper response back. Since it works fine in the console but breaks through API Gateway, you’re probably not handling the event structure correctly. API Gateway wraps your request data differently than direct testing does. Make sure you’re parsing event.body as JSON before trying to access your apiData property. Also, your Lambda needs to always return a response object with statusCode, headers, and body - even when things go wrong. Wrap your main code in try-catch blocks so it doesn’t crash silently and actually returns error responses.