typescriptintermediate

AWS SDK v3 — S3 Operations in TypeScript

Perform S3 operations with AWS SDK v3: upload, download, list, presigned URLs, and multipart upload.

typescript
import {
  S3Client,
  PutObjectCommand,
  GetObjectCommand,
  ListObjectsV2Command,
} from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { readFileSync } from 'fs';

const s3 = new S3Client({ region: 'us-east-1' });
const BUCKET = 'my-app-uploads';

// Upload a file
async function upload(key: string, filePath: string): Promise<string> {
  await s3.send(new PutObjectCommand({
    Bucket: BUCKET,
    Key: key,
    Body: readFileSync(filePath),
    ContentType: 'application/octet-stream',
  }));
  return `s3://${BUCKET}/${key}`;
}

// Generate presigned download URL (valid 1 hour)
async function getDownloadUrl(key: string): Promise<string> {
  const command = new GetObjectCommand({ Bucket: BUCKET, Key: key });
  return getSignedUrl(s3, command, { expiresIn: 3600 });
}

// List objects with prefix
async function listObjects(prefix: string) {
  const result = await s3.send(new ListObjectsV2Command({
    Bucket: BUCKET,
    Prefix: prefix,
    MaxKeys: 100,
  }));
  return result.Contents?.map(obj => ({
    key: obj.Key!,
    size: obj.Size!,
    modified: obj.LastModified!,
  })) ?? [];
}

// Generate presigned upload URL (client-side upload)
async function getUploadUrl(key: string): Promise<string> {
  const command = new PutObjectCommand({ Bucket: BUCKET, Key: key });
  return getSignedUrl(s3, command, { expiresIn: 300 });
}

Sponsored

Cloudflare R2

Use Cases

  • Server-side file uploads to S3
  • Generating presigned URLs for client-side uploads
  • Listing and managing S3 objects programmatically

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.