JavaScript용 AWS SDK (aws-sdk)로 R2 사용하기
JavaScript/TypeScript에서 aws-sdk 패키지로 R2를 사용하는 예시예요. S3 클라이언트에 R2 자격 증명을 전달하고 버킷·객체를 나열하며, CORS·Content-Type 제한이 적용된 사전 서명 URL까지 생성하는 방법을 보여줘요.
출처: 문서
본문
AWS JavaScript SDK의 최신 버전에 관심이 있다면 전용 aws-sdk-js-v3 예시 페이지를 참고하세요.
JavaScript나 TypeScript 사용자는 평소처럼 aws-sdk ↗︎ npm 패키지를 계속 사용할 수 있어요. S3 서비스 클라이언트를 만들 때 R2 구성 자격 증명을 반드시 전달해야 해요.
import S3 from "aws-sdk/clients/s3.js";
const s3 = new S3({
// 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)
accessKeyId: `${ACCESS_KEY_ID}`,
secretAccessKey: `${SECRET_ACCESS_KEY}`,
signatureVersion: "v4",
});
console.log(await s3.listBuckets().promise());
//=> {
//=> 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.listObjects({ Bucket: "my-bucket" }).promise());
//=> {
//=> IsTruncated: false,
//=> Name: 'my-bucket',
//=> CommonPrefixes: [],
//=> MaxKeys: 1000,
//=> Contents: [
//=> {
//=> Key: 'cat.png',
//=> LastModified: 2022-05-07T02:50:45.616Z,
//=> ETag: '"c4da329b38467509049e615c11b0c48a"',
//=> ChecksumAlgorithm: [],
//=> Size: 751832,
//=> Owner: [Object]
//=> },
//=> {
//=> Key: 'todos.txt',
//=> LastModified: 2022-05-07T21:37:17.150Z,
//=> ETag: '"29d911f495d1ba7cb3a4d7d15e63236a"',
//=> ChecksumAlgorithm: [],
//=> Size: 279,
//=> Owner: [Object]
//=> }
//=> ]
//=> }
사전 서명 URL 생성 (Generate presigned URLs)
버킷에 대한 공개 읽기 또는 쓰기 접근 권한을 일시적으로 공유하는 데 사용할 수 있는 사전 서명 링크도 생성할 수 있어요.
// Use the expires property to determine how long the presigned link is valid.
console.log(
await s3.getSignedUrlPromise("getObject", {
Bucket: "my-bucket",
Key: "dog.png",
Expires: 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 s3.getSignedUrlPromise("putObject", {
Bucket: "my-bucket",
Key: "dog.png",
Expires: 3600,
ContentType: "image/png",
}),
);
https://my-bucket.<ACCOUNT_ID>.r2.cloudflarestorage.com/dog.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=<credential>&X-Amz-Date=<timestamp>&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=<signature>
https://my-bucket.<ACCOUNT_ID>.r2.cloudflarestorage.com/dog.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=<credential>&X-Amz-Date=<timestamp>&X-Amz-Expires=3600&X-Amz-SignedHeaders=content-type%3Bhost&X-Amz-Signature=<signature>
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 제한: 사전 서명 URL 매개변수에 허용된 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 s3.getSignedUrlPromise("putObject", {
Bucket: "my-bucket",
Key: "user-upload.png",
Expires: 3600,
ContentType: "image/png",
});
클라이언트가 이 사전 서명 URL을 사용할 때는 반드시 다음을 지켜야 해요:
-
허용된 오리진에서 요청할 것 (CORS로 강제됨)
-
Content-Type: image/png헤더를 포함할 것 (서명으로 강제됨)