Setup AWS S3 bucket for NodeJS

raviagheda

Ravi Agheda

Posted on January 7, 2023

Setup AWS S3 bucket for NodeJS

Amazon Simple Storage Service (S3) is one of the best tool to store the file/media. Let's set it up with nodejs framework.

  1. Setup S3 bucket with public access.
  2. Integrate S3 with NodeJS.

1. Setup S3 bucket with public access.

First thing first, let's create a bucket
Create Bucket Image

Enter the name and Change the region if required, here I'm keeping it Oregon as default.
Enter Bucket Name Image

As I need a public bucket so I'm enabling a ACL and keeping Radio options as it is.

Enable ACL Image

Same as above, uncheck the checkbox in order to make it public.
Block Public Access Image

Acknowledgement Image

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.

  1. Open a Bucket
  2. 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/*"
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode
  • Scroll down to CORS policy and Edit
[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET",
            "PUT",
            "POST"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": []
    }
]
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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/ ).

đź’– đź’Ş đź™… đźš©
raviagheda
Ravi Agheda

Posted on January 7, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related