Setup AWS S3 bucket for NodeJS
Ravi Agheda
Posted on January 7, 2023
Amazon Simple Storage Service (S3) is one of the best tool to store the file/media. Let's set it up with nodejs framework.
- Setup S3 bucket with public access.
- Integrate S3 with NodeJS.
1. Setup S3 bucket with public access.
First thing first, let's create a bucket
Enter the name and Change the region if required, here I'm keeping it Oregon as default.
As I need a public bucket so I'm enabling a ACL and keeping Radio options as it is.
Same as above, uncheck the checkbox in order to make it public.
Keep rest of the options as it is unless required, and hit create bucket button.
Now once bucket is created we would have to update the bucket policy in order to access it as public bucket.
- Open a Bucket
- Go to permission and scroll down to Bucket Policy, and Edit
{
"Version": "2008-10-17",
"Statement": [
{
"Sid": "AllowPublicRead",
"Effect": "Allow",
"Principal": {
"AWS": "*"
},
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::ravis-blog-bucket/*"
}
]
}
- Scroll down to CORS policy and Edit
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"GET",
"PUT",
"POST"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": []
}
]
Make sure that you update the bucket name inside the policy code "Resource".
In order to test the setup, upload a single file and try to access it from outside, i.e. Incognito.
2. Integrate S3 with NodeJS
Assuming you already have express app setup and we are ready to proceed with aws sdk setup. In order to acccess S3 apis from nodejs we would need to install aws-sdk
npm package.
Lets also install the uuid
and mime
as helper packages.
const { S3 } = require('aws-sdk');
const uuid = require('uuid').v4;
const mime = require("mime");
const s3 = new S3();
const uploader = (file, filepath) => {
console.log("uploading file -> ", file);
const params = {
Bucket: process.env.AWS_S3_BUCKET, // ravis-blog-bucket
Key: `${filepath}${uuid()}_${Date.now()}_.${mime.getExtension(file.mimetype)}`,
Body: file.buffer
};
console.log(params);
return s3.upload(params);
}
Now it's ready for user, we can call the uploader function and pas multipart file and filePath ( location path at S3, i.e. images/logos/ ).
Posted on January 7, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.