Skip to content

Instantly share code, notes, and snippets.

@katendeglory
Last active July 19, 2023 20:01
Show Gist options
  • Save katendeglory/f7bc4fb23ec372fcbeae52c08ff16194 to your computer and use it in GitHub Desktop.
Save katendeglory/f7bc4fb23ec372fcbeae52c08ff16194 to your computer and use it in GitHub Desktop.
How to PUT/GET Files to aws S3 directly from a React Client using a generated pre-signed url endpoint
// NODE-JS SIDE------------------------------------------------------------------------------------
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
AWS.config.update({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
});
/**
* @param {string} key - Object path
* @param {('getObject'|'putObject'|'deleteObject')} operation - HTTP Method
* @returns {string} - A Temporar URL Endpoint
*/
async function getSignedURLEndpoint(key, operation) {
var options = {
Bucket: process.env.AWS_BUCKET,
Key: key, /* Filename in the bucket */
Expires: 3000 /* Seconds */
};
const url = await s3.getSignedUrlPromise(operation, options);
return url;
}
// REACT-JS SIDE GET ------------------------------------------------------------------------------
import axios from 'axios';
const GETEndpoint = getSignedURLEndpoint('project-1/avatar/theosassler.png', 'getObject');
axios.get(GETEndpoint)
.then(res => console.log(res))
.catch(err => console.log(err));
// REACT-JS SIDE PUT -----------------------------------------------------------------------------
import axios from 'axios';
const PUTEndpoint = getSignedURLEndpoint('project-1/avatar/theosassler.png', 'putObject');
const options = {
params: { Key: file.name, ContentType: file.type },
headers: { 'Content-Type': file.type }
};
axios.put(PUTEndpoint, file, options)
.then(res => console.log(res))
.catch(err => console.log(err));
// AWS CONFIG--------------------------------------------------------------------------------------
` 1. S3 Bucket setting
2. Create a DNS compliant bucket name
3. Set default encryption
4. Give appropriate read and write permissions
5. Add following CORS rules
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>HEAD</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment