Skip to content

Instantly share code, notes, and snippets.

@tomfa
Last active December 20, 2021 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomfa/fc903cec26dff19ca6d583c94f460c2f to your computer and use it in GitHub Desktop.
Save tomfa/fc903cec26dff19ca6d583c94f460c2f to your computer and use it in GitHub Desktop.
Upload to S3 from Typescript
// Demo of creating upload urls to AWS S3.
// See github.com/tomfa/nextjs-s3-upload for a complete app
import {
S3Client,
PutObjectCommand,
} from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
const s3 = new S3Client({
region: process.env.S3_BUCKET_REGION, // e.g. 'eu-central-1',
credentials: {
accessKeyId: process.env.SECRET_AWS_ACCESS_KEY_ID as string,
secretAccessKey: process.env.SECRET_AWS_SECRET_ACCESS_KEY as string,
},
});
type GetUploadUrlProps = {
folder: string;
filename: string;
acl?: "public-read" | "private";
options?: { expiresIn?: number };
};
export const getUploadUrl = async ({
folder,
filename,
acl = "public-read",
options: {
expiresIn = 15 * 60 // 15 minutes
} = {},
}: GetUploadUrlProps): Promise<{ signedUrl: string; key: string }> => {
const key = `${folder}/${filename}`;
const command = new PutObjectCommand({
Bucket: config.s3.bucketName,
Key: key,
ACL: acl,
});
return getSignedUrl(s3, command, { expiresIn });
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment