JavaScript용 AWS SDK v3 (aws-sdk-js-v3)로 R2 사용하기
JavaScript/TypeScript용 새 AWS SDK v3(@aws-sdk/client-s3)로 R2를 사용하는 예시예요. S3Client를 만들고 버킷·객체를 조회하며 사전 서명 URL을 생성하는 방법을 다뤄요.
출처: 문서
본문
JavaScript나 TypeScript 사용자는 평소처럼 @aws-sdk/client-s3 ↗︎ npm 패키지를 계속 사용할 수 있어요. S3 서비스 클라이언트를 만들 때 R2 구성 자격 증명을 반드시 전달해야 해요.
import {
S3Client,
ListBucketsCommand,
ListObjectsV2Command,
GetObjectCommand,
PutObjectCommand,
} from "@aws-sdk/client-s3";
const S3 = new S3Client({
region: "auto", // Required by SDK but not used by R2
// Provide your Cloudflare account ID
endpoint: `https://${ACCOUNT_ID}.r2.cloudflarestorage.com`,
// Retrieve your S3 API credentials for your R2 bucket via API tokens (see: https://developers.cloudflare.com/r2/api/tokens)
credentials: {
accessKeyId: ACCESS_KEY_ID,
secretAccessKey: SECRET_ACCESS_KEY,
},
});
console.log(await S3.send(new ListBucketsCommand({})));
// {
// '$metadata': {
// httpStatusCode: 200,
// requestId: undefined,
// extendedRequestId: undefined,
// cfId: undefined,
// attempts: 1,
// totalRetryDelay: 0
// },
// Buckets: [
// { Name: 'user-uploads', CreationDate: 2022-04-13T21:23:47.102Z },
// { Name: 'my-bucket', CreationDate: 2022-05-07T02:46:49.218Z }
// ],
// Owner: {
// DisplayName: '...',
// ID: '...'
// }
// }
console.log(
await S3.send(new ListObjectsV2Command({ Bucket: "my-bucket" })),
);
// {
// '$metadata': {
// httpStatusCode: 200,
// requestId: undefined,
// extendedRequestId: undefined,
// cfId: undefined,
// attempts: 1,
// totalRetryDelay: 0
// },
// CommonPrefixes: undefined,
// Contents: [
// {
// Key: 'cat.png',
// LastModified: 2022-05-07T02:50:45.616Z,
// ETag: '"c4da329b38467509049e615c11b0c48a"',
// ChecksumAlgorithm: undefined,
// Size: 751832,
// StorageClass: 'STANDARD',
// Owner: undefined
// },
// {
// Key: 'todos.txt',
// LastModified: 2022-05-07T21:37:17.150Z,
// ETag: '"29d911f495d1ba7cb3a4d7d15e63236a"',
// ChecksumAlgorithm: undefined,
// Size: 279,
// StorageClass: 'STANDARD',
// Owner: undefined
// }
// ],
// ContinuationToken: undefined,
// Delimiter: undefined,
// EncodingType: undefined,
// IsTruncated: false,
// KeyCount: 8,
// MaxKeys: 1000,
// Name: 'my-bucket',
// NextContinuationToken: undefined,
// Prefix: undefined,
// StartAfter: undefined
// }
사전 서명 URL 생성 (Generate presigned URLs)
버킷에 대한 공개 읽기 또는 쓰기 접근 권한을 일시적으로 공유하는 데 사용할 수 있는 사전 서명 링크도 생성할 수 있어요.
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
// Use the expiresIn property to determine how long the presigned link is valid.
console.log(
await getSignedUrl(
S3,
new GetObjectCommand({ Bucket: "my-bucket", Key: "dog.png" }),
{ expiresIn: 3600 },
),
);
// You can also create links for operations such as PutObject to allow temporary write access to a specific key.
// Specify ContentType to restrict uploads to a specific file type.
console.log(
await getSignedUrl(
S3,
new PutObjectCommand({
Bucket: "my-bucket",
Key: "dog.png",
ContentType: "image/png",
}),
{ expiresIn: 3600 },
),
);
https://my-bucket.<ACCOUNT_ID>.r2.cloudflarestorage.com/dog.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=<credential>&X-Amz-Date=<timestamp>&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=<signature>&x-id=GetObject
https://my-bucket.<ACCOUNT_ID>.r2.cloudflarestorage.com/dog.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=<credential>&X-Amz-Date=<timestamp>&X-Amz-Expires=3600&X-Amz-SignedHeaders=content-type%3Bhost&X-Amz-Signature=<signature>&x-id=PutObject
PutObject 예시로 생성한 링크를 사용해서 사전 서명 링크가 만료되기 전까지 지정된 버킷과 키에 업로드할 수 있어요. ContentType이 포함된 사전 서명 URL을 사용할 때는 클라이언트가 요청에 일치하는 Content-Type 헤더를 꼭 포함해야 해요.
curl -X PUT "https://my-bucket.<ACCOUNT_ID>.r2.cloudflarestorage.com/dog.png?X-Amz-Algorithm=..." \
-H "Content-Type: image/png" \
--data-binary @dog.png
CORS와 Content-Type으로 업로드 제한하기 (Restrict uploads with CORS and Content-Type)
업로드용 사전 서명 URL을 생성할 때 다음 방법으로 남용과 오용을 제한할 수 있어요:
-
Content-Type 제한:
PutObjectCommand에서 허용된 content type을 지정해요. 클라이언트가 다른Content-Type헤더를 보내면 업로드는 실패해요. -
CORS 구성: 버킷에 CORS 규칙을 설정해 어떤 오리진이 파일을 업로드할 수 있는지 제어해요. Cloudflare 대시보드 ↗︎에서 버킷 설정에 JSON 정책을 추가해 CORS를 구성할 수 있어요:
[
{
"AllowedOrigins": ["https://example.com"],
"AllowedMethods": ["PUT"],
"AllowedHeaders": ["Content-Type"],
"ExposeHeaders": ["ETag"],
"MaxAgeSeconds": 3600
}
]
그다음 Content-Type 제한이 적용된 사전 서명 URL을 생성해요:
const putUrl = await getSignedUrl(
S3,
new PutObjectCommand({
Bucket: "my-bucket",
Key: "dog.png",
ContentType: "image/png",
}),
{ expiresIn: 3600 },
);
클라이언트가 이 사전 서명 URL을 사용할 때는 반드시 다음을 지켜야 해요:
-
허용된 오리진에서 요청할 것 (CORS로 강제됨)
-
Content-Type: image/png헤더를 포함할 것 (서명으로 강제됨)