Dhaval Vira 👋
A Passionate Full Stack Developer 🖥️ with 1.10+ Years of experience.
04-Oct-2023
Mastering AWS S3 Image Upload with Nextjs: A Detailed Guide
Hello guys, today in this blog article we are going to explore & see how we can upload images to AWS S3 using Next.js after a lot of hustles & problems, I was unable to find a proper solution to use AWS SDK to upload Images to S3 Bucket using Next.js after that I find a solution & writing an article on it.
In this article, we are going to use SDK from AWS for S3 and Axios, and we are going to download 2 NPM packages required to achieve this.
npm install aws-sdk
The above command will install the official SDK npm package from AWS in order to use the functionality of S3 to upload Images to AWS S3 Bucket.
npm install axios
The above command will install the Axios package to make HTTPS calls to API End Points or to Next.js Serverless APIs.
Now we are going to see the code example to see how we can upload the image to AWS S3 Bucket.
Here we can have 2 options, 1. want to use 1 form only or multiple forms, first, we’re going to explore how we can use a single form.
import aws from 'aws-sdk'
import axios from 'axios'
const AppName = () => {
// some hooks to store the form values + image in array
// updating the S3 Config
aws.config.update({
accessKeyId: process.env.accessKeyId,
secretAccessKey: process.env.secretAccessKey,
region: process.env.region,
signatureVersion: 'v4',
})
// creating Object from AWS S3 SDK
const s3 = new aws.S3({ apiVersion: '2006-03-01' });
try {
s3.upload(
{
Bucket: process.env.bucketName,
Key: file.name, // this KEY will be the name of the Image file
Body: file, // this will be the actual file uploaded from FORM
},
{
async (err, data) => {
if (data) {
some other variable of form fields
let imageURLFromS3 = data.Location
let formData = {
some other variable of form fields,
imageURLFromS3
}
axios.post(`your-api-url`, formData)
.then().catch()
}
else if (err) console.log(err)
}
}
)
} catch (err) console.log(err);
return (
// your form and other sections
)
}
export default AppName
In Axios, we can either pass the API End Point which is located/hosted somewhere else or we can pass the path of Next.js Serverless API which can be like /api/fileName
Now we will create the helper function for the same which we can use at multiple places.
import aws from 'aws-sdk';
export const getS3Object = async () => {
aws.config.update({
accessKeyId: process.env.accessKeyId,
secretAccessKey: process.env.secretAccessKey,
region: process.env.region,
signatureVersion: 'v4',
});
const s3 = new aws.S3({ apiVersion: '2006-03-01' });
return s3;
};
Now we can import this helper function wherever we need it.
We can import the package like below in the required files/page.
import { getS3Object } from '/path/to/your/helper/function/file;
const uploadFunc = async () => {
const s3 = await getS3Object();
s3.upload({
Bucket: process.env.bucketName,
Key: uploadNewImage.name,
Body: uploadNewImage,
}, (err, data) => {
if (data) setFileUrl(data.Location)
else if (err) console.log(err)
}
}
After creating/updating the AWS configuration with accessKey, secretAccessKey, region, and signatureVersion we are creating an object from SDK called S3 bypassing a apiVersion, and after that, we’re using the upload the method from S3.
And in s3.upload()
, we’re using a function, this function has 2 parameters:
data ==> returns when the Image is successfully uploaded to S3 Bucket and returns the entire object along with the URL of the uploaded image which can be accessed by
data.Location
err ==> if the s3 object (created from AWS SDK) is failed due to some reasons (e.g. CORS or S3 Bucket access) this will be used.
The image I’ve used – is AWS S3 its rights & copyright are of Amazon & AWS.
Stay Tunned
The best articles, links and news related to web development delivered once a week to your inbox.