iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
😑
Sample Code for S3 Presigned URLs in AWS SDK v3
I was stuck for a while because I encountered a NET::ERR_CERT_COMMON_NAME_INVALID error. This happened because when I provided an endpoint to the S3Client, the returned presignedUrl had a duplicated bucket name, such as hoge-bucket.hoge-bucket.s3-ap-northeast-1.amazonaws.com/hoge. It seems you should not specify the endpoint in a production environment.
import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
const fileName = 'hoge';
const fileType = 'jpg';
const client = new S3Client({
region: process.env.S3_REGION,
endpoint: process.env.S3_ENDPOINT, // Specify the LocalStack URL only during development. This should be undefined in production.
forcePathStyle: process.env.S3_FORCE_PATH_STYLE, // Set this to true only during development because LocalStack only supports path style.
});
const key = '${fileName}-${Date.now()}`; // Append a hash at the end to avoid duplicate filenames.
const params = {
Bucket: process.env.S3_BUCKET_NAME,
Key: key,
ContentType: fileType,
};
const command = new PutObjectCommand(params);
const url = await getSignedUrl(client, command, { expiresIn: 3600 });
console.log(url);
Discussion