How to upload Image to AWS S3 using Nextjs

How to upload Image to AWS S3 using Nextjs

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 the AWS for S3 and Axios, and we are going to download 2 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.

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

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:

  1. 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

  2. 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 – AWS S3 its rights & copyright are of Amazon & AWS.

to know more about me or want to read relevant & more blogs, find me on my website