Serverless functions not working with React app after local build

I’ve found a solution :partying_face: I’ll walk you through my process.

After adding headers to my function responses per this topic, I saw a more precise error in the console when I call my functions in production:

502
error decoding lambda response: invalid status code returned from lambda: 0

Turns out there have been multiple Netlify topics opened on this very error, concerning all sorts of problems/solutions that didn’t bring me any further.

However, I did come across the suggestion to add some logging to my function code. (Even though this may sound obvious in terms of debugging purposes, it hadn’t been abundantly clear to me up until that point that you can view a real-time console in the function section of your dashboard.)

This is the code that I redeployed:

exports.handler = async (event, context) => {
  
  let response

  try {
    response = await axios.get(`${process.env.REACT_APP_PROD_API_URL}/districts`, {
        headers: {
            "Authorization": `JWT ${process.env.REACT_APP_PROD_JWT_TOKEN}`,
            "Accept": "application/json", 
            "Content-Type": "application/json"
        }
    })

  } catch (err) {

    console.log(err)  // added this new line
    
    return {
      statusCode: err.statusCode,
      body: JSON.stringify({
        error: err.message
      }),
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Credentials": "true",
        "Content-Type": "application/json"
      },
    }
  }

  return {
    statusCode: 200,
    body: JSON.stringify({
      data: response.data
    }),
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Credentials": "true",
      "Content-Type": "application/json"
    },
  }
}

I looked at the console, and among the logs I spotted the following:

url: '"https://myapidomain.com/api/v1"/districts',

I went to the environment variables section of my dashboard and sure enough, I’d added my variables with quotation marks around them. This is not necessary, as Netlify will process them as strings by default!

So I removed the quotation marks, redeployed, et voilà. All along, the problem had been the darn quotation marks.

Thanks @hrishikesh for your time on this. Hope this helps someone else!