/

How to Upload Files to S3 from Node.js

How to Upload Files to S3 from Node.js

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:

  1. An AWS account. If you don’t have one, you can sign up at https://aws.amazon.com.
  2. Create an IAM user in AWS. Log in to AWS, click your name on top, and select “My Security Credentials”.

Create an IAM User

  1. On the sidebar, click on “Users” and then “Add user”. Enable “Programmatic access”.
  2. Move to the next screen by clicking the buttons at the bottom of the page (“Next: Permissions”).
  3. Click on “Attach existing policies directly” and type “S3” in the filter to show the S3 policies.
  4. Select the “AmazonS3FullAccess” permission.
  5. 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

  1. Go to the S3 homepage at https://s3.console.aws.amazon.com and click on the “Create bucket” button.
  2. 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.

  1. Install the aws-sdk package by running npm install aws-sdk.
  2. Store your AWS access codes in the .env file:
1
2
3
AWS_ACCESS_KEY_ID=<your-access-key>
AWS_SECRET_ACCESS_KEY=<your-secret-access-key>
AWS_BUCKET_NAME=<your-bucket-name>
  1. Import the AWS module at the top of your file:
1
import AWS from 'aws-sdk';
  1. Initialize the s3 object:
1
2
3
4
const s3 = new AWS.S3({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
});
  1. To upload a file, load it from storage:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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