Skip to main content

Download S3 Image File

  • Node endpoint to download files within s3 bucket
  • Make sure you have all the proper env configs

Code​

const AWS = require("aws-sdk");

AWS.config.update({
accessKeyId: process.env["ACCESS_KEY_ID"],
secretAccessKey: process.env["SECRET_ACCESS_KEY"],
region: process.env["REGION"],
});

const s3 = new AWS.S3();

export default async function handler(req, res) {
try {
const { key } = req.query;
if (!key) {
return res.status(400).json({ error: "File key is required" });
}

const params = {
Bucket: process.env["BUCKET"],
Key: key,
};

const data = await s3.getObject(params).promise();
if (!data.Body) {
return res.status(404).json({ error: "File not found" });
}

res.setHeader("Content-Type", "image/jpeg");
res.end(data.Body, "binary");
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal server error" });
}
}