In this tutorial, I will guide you on how to upload files to AWS S3 from Node.js. The scenario I encountered was building a job board where recruiters can submit a new job offer along with a company logo image. Storing the image in the database turned out to be inefficient, so I decided to upload it to S3.
Prerequisites
Before we begin, here are the prerequisites:
- An AWS account. If you don’t have one, you can sign up at https://aws.amazon.com.
- Create an IAM user in AWS. Log in to AWS, click your name on top, and select “My Security Credentials”.
Create an IAM User
- On the sidebar, click on “Users” and then “Add user”. Enable “Programmatic access”.
- Move to the next screen by clicking the buttons at the bottom of the page (“Next: Permissions”).
- Click on “Attach existing policies directly” and type “S3” in the filter to show the S3 policies.
- Select the “AmazonS3FullAccess” permission.
- Once the user is created, you’ll receive a pair of access key ID and secret access key. Copy these credentials to your
.env
file or store them securely for later use.
Create an S3 Bucket
- Go to the S3 homepage at https://s3.console.aws.amazon.com and click on the “Create bucket” button.
- Set a name for your bucket, choose an AWS region, disable “Block all public access” (permissions will be covered in another post), and click the “Create bucket” button at the bottom of the page.
Setting Up Node.js
Now that we have created an S3 bucket, let’s dive into the Node.js code. Note that in this example, I am using Next.js on the server-side for an API call.
- Install the
aws-sdk
package by runningnpm install aws-sdk
. - Store your AWS access codes in the
.env
file:
AWS_ACCESS_KEY_ID=<your-access-key>
AWS_SECRET_ACCESS_KEY=<your-secret-access-key>
AWS_BUCKET_NAME=<your-bucket-name>
- Import the
AWS
module at the top of your file:
import AWS from 'aws-sdk';
- Initialize the
s3
object:
const s3 = new AWS.S3({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
});
- To upload a file, load it from storage:
const filename = 'the-file-name';
const fileContent = fs.readFileSync(fileName);
const params = {
Bucket: process.env.AWS_BUCKET_NAME,
Key: `${filename}.jpg`,
Body: fileContent,
};
s3.upload(params, (err, data) => {
if (err) {
reject(err);
}
resolve(data.Location);
});
That’s it! You have now successfully uploaded a file to the S3 bucket from Node.js.
Tags: AWS, S3, Node.js, file upload