Search code examples
amazon-web-servicesamazon-s3aws-sdkaws-sdk-js

How do I get response headers for AWS JavaScript SDK calls?


I have a simple AWS Lambda function which makes an S3.getObject() call as follows:

const AWS = require('aws-sdk');

AWS.config.logger = console;

const s3 = new AWS.S3();

exports.handler = async (event) => {
  return await getObject({
    Bucket: "<MY-BUCKET>", 
    Key: "<MY-KEY>"
  }).then( (res) => {
    console.log('Retrieved object from S3');
    console.log(res);
    return res.Body.toString('ascii');
  })
};

async function getObject(params){
  return await s3.getObject(params).promise();
}

I've enabled logging SDK calls as per this document.

How do I get response headers for the s3.getObject() SDK call that was made? I am basically trying to retrieve the S3 request ID and extended request ID.

The in-built logger added via the "AWS.config.logger = console;" line does not seem to log response headers. How else do I get response headers for AWS JavaScript SDK calls?

P.S: Bonus points if you can let me know whether or not I need two await keywords in the code above.


Solution

  • Listen to httpHeaders event.

    var requestObject = s3.getObject(params);
    
    requestObject.on('httpHeaders', (statusCode, headers, response, statusMessage) => {
        // your code here.
    });
    
    requestObject.promise()
        .then(response => { ... })