How to securely upload images to amazon S3 from a Next JS application?

Viewed 1233

Im building a NextJS application and I need authorised users to be able to upload images to Amazon S3 bucket, for use on posts.

Whats the best way to go about it? I've had a look around, but can only find tutorials for uploading via express, or using a react-s3 package that runs on the front end, but I'm wary about storing sensitive data for the amazon s3 in the front end code.

Can I write a lamda function in an api route on next and send from there? Or is there a secure way to upload from the font end. I have very little experience with BE so not much experience with express etc... but any help would be much appreciated.

1 Answers

so you have to create in the api folder a file with this function

import aws from "aws-sdk";
 aws.config.update({
    accessKeyId: "your id ",
    secretAccessKey: "your secret ",
    region: "your bucket region",
    signatureVersion: 'v4',
  });
  const s3 = new aws.S3();
  const post = await s3.createPresignedPost({
    Bucket: "your bucket name",
    Fields: {
      key: req.query.file,
    },
    Expires: 600, // seconds
    ACL:"public-read",
    Conditions: [
      ['content-length-range', 0, 12048576], 
    ],
  });

if you call this api it will give you back a link url with some data to put in the header to access for 10 min to upload the image and if you fetch this url with the file you will upload to the bucket in s3

const res = await fetch(
  `${server}/api/admin/add/addImage?file=${file.name}`
);

const { url, fields } = await res.json();
const formData = new FormData();

Object.entries({ ...fields, file }).forEach(([key, value]) => {
  formData.append(key, value);
});

const upload = await fetch(url, {
  method: "POST",
  body: formData,
});
setUrlfileUploaded(`${upload.url}/${file.name}`);

if (upload.ok) {
  console.log("Uploaded successfully!");
} else {
  console.error("Upload failed.");
}
Related