Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a CORS header to this Lambda function

Please bare with me as this is my first stack overflow post, but I have minimal backend experience and am really struggling to meet CORS requirements.

I want to use AWS (SES, API Gateway, Lambda) to send form data to our company email account. My function works currently when testing in AWS, but it doesn't work on the client side of my site. From what I've gathered from research so far, my Lambda function needs a CORS header to work. Here is the code:

var aws = require("aws-sdk");
var ses = new aws.SES({ region: "us-east-1" });

exports.handler = async function(payload) {
  var params = {
    Destination: {
      ToAddresses: ['[email protected]'],
    },
    Message: {
      Body: {
        Text: {
          Data: `\n
        ${payload.fullName} has tried to contact you. \n
        Message: \n
        -------------------- \n
        ${payload.comments} \n
        -------------------- \n
        Here is the sender's contact information: \n 
        Name: ${payload.fullName} \n
        Email: ${payload.emailAddress} \n
        Phone: ${payload.phone} \n
        Company: ${payload.companyName}`
        },
      },

      Subject: { Data: payload.subject },
    },
    Source: '[email protected]',
  };


  return ses.sendEmail(params).promise()
};

I'm looking at this code as an example of how to include a CORS header:

exports.handler = async (event) => {
  let data = {};
  let res =  {
    statusCode: 200,
    headers: { 
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*' // replace with hostname of frontend (CloudFront)
    },
    body: JSON.stringify(data)
  };
  return res;
};

Can anyone help me to combine these two approaches? I don't understand how to make the SES function into a more traditional response. I am mostly a frontend dev, so I expect that I'm missing something silly. I appreciate any responses though.

like image 478
Tarell Morris Avatar asked Mar 09 '26 17:03

Tarell Morris


1 Answers

If you can change the API Gateway integration type to Lambda Proxy, then this code can help you.

Move the entire code in the handler method to another function say sendEmail

const sendEmail =  async function(payload) {
  // Your code to crete the `params` omitted for brevity
  return ses.sendEmail(params).promise()
};

The handler can call this function and based on the outcome of this function send an appropriate result with the CORS headers

exports.handler = async function(event) {
  const payload = JSON.parse(event.body);
  const CORS_HEADERS = { 
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*' // Your origin name
  };
  try {
    await sendEmail(payload);
    return {
      statusCode: 200,
      headers: CORS_HEADERS,
      body: '{}'
    }
  } catch(err) {
    return {
      statusCode: 500, // Can be 4XX or 5XX depending on the error
      headers: CORS_HEADERS,
      body: `{"err": ${err.messge}}`
    }
  }
}

For this to work for CORS requests, you also need to ensure the OPTIONS request responds with appropriate headers. You can do so using the AWS console following this documentation. For CloudFormation along with api-gateway V2, this documentation should help. For AWS SAM, this documentation should help (If you are not already using any Serverless development tool, take a look at AWS SAM).

If you don't wish to use the Lambda proxy, then ensure the integration response send the appropriate CORS headers for both the OPTIONS request and the POST request. This can help.

like image 60
GSSwain Avatar answered Mar 11 '26 05:03

GSSwain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!