How to send metadata along with S3 signedUrl in Node.js?

Soni Pandey
2 min readJul 8, 2020

In this article, we’ll learn about how to send metadata along with the signedUrl and how to retrieve metadata of that file. Recently I found some challenges to achieve this in Node.js (Javascript). So, writing this article to make it easier for others based on my experience.

How to generate signedUrl along with metadata?

const AWS = require('aws-sdk');
async function createSignedUrl(key, metadata){
const myBucket = 'bucketName';
const myKey = key;
const signedUrlExpireSeconds = 60 * 60;
const s3 = new AWS.S3({
signatureVersion: 'v4'
});
const params = {
Bucket: myBucket,
Key: myKey,
Expires: signedUrlExpireSeconds,
Metadata: metadata
};
return new Promise((resolve, reject) => {
s3.getSignedUrl('putObject', params, (err, url) => {
if (err) {
reject(err);
}
else {
resolve(url);
}
})
})
}

We’ll pass metadata object also in params for generating signedUrl. Metadata object look like:

metadata: {
id: "0b5e4838-a6a0-4784-98d8-c58a76201957",
count: "100",
name: "69a62347-8641-45ba-9924-39f84ee3fbd8_1591723404.txt"
}

All values of metadata object should be string, otherwise you’ll get error. Once the signed url generated, we’ll use signed url for uploading file.

While uploading the file through signedUrl, please make sure that all metadata keys are attached to header along with content-type in similar format:

x-amz-meta-id: ‘0b5e4838-a6a0–4784–98d8-c58a76201957’,
x-amz-meta-count: '100',
x-amz-meta-name: '69a62347-8641-45ba-9924-39f84ee3fbd8_1591723404.txt'
content-type: 'jpg' // this'll be the extension of file which we're uploading

How to get metadata of s3 file?

const getMetadata = async (key) => {
const params = {
Bucket: 'bucketName', // bucket name
Key: 'key' // file name
};
return await s3.headObject(params).promise();
}
const {Metadata} = await getMetadata('key'); //key_name of s3 file
Metadata will look like -
{
id: "0b5e4838-a6a0-4784-98d8-c58a76201957",
count: "100",
name: "69a62347-8641-45ba-9924-39f84ee3fbd8_1591723404.txt"
}

NOTE: Please replace the bucketName and key values with original data.

Conclusion:

This article was about S3 metadata insights. How can we send metadata along with S3 file and retrieve metadata.

Hope you find the article useful.

--

--

Soni Pandey

I am a Node.js Developer and eager to learn new technology. I blog, tweet & read whenever I can.