Setup AWS S3 bucket for NodeJS
🪣

Setup AWS S3 bucket for NodeJS

Published
Published January 7, 2023
Author
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.
  1. Integrate S3 with NodeJS.

1. Setup S3 bucket with public access.

First thing first, let's create a bucket
notion image
Enter the name and Change the region if required, here I'm keeping it Oregon as default.
notion image
As I need a public bucket so I'm enabling a ACL and keeping Radio options as it is.
notion image
Same as above, uncheck the checkbox in order to make it public.
notion image
notion 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
  1. 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/*" } ] }
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/ ). Thank you for reading through.