AWS SDK を使ったブラウザーから Cloudflare R2 へのアップロード
ブラウザーに R2 のシークレットキーを渡さずに、非公開の Cloudflare R2 バケットへ直接アップロードできます。以下の小さなローカルアプリを実行してみてください。アップロードを要求するユーザーを認証し、単一のオブジェクトキーに署名して、保存されたバイト列を確認してから成功を表示します。
権限の管理はサーバー側で
AWS SDK は Node.js サーバー上で動作します。ブラウザーは単一オブジェクト用の署名付き PUT URL を受け取り、ファイルを R2 に送信してから、サーバーに読み戻しを要求します。保存されたサイズと SHA-256 ダイジェストを選択したファイルと比較することで、HTTP 転送が成功していても、誤ったバイト列が保存されたケースを検出します。
これは、ゼロバイトから 10 MiB までのファイルを扱う、単一ユーザー向けのローカルデモです。アクセスコードで一人のローカルユーザーを識別し、サーバーがそのユーザーのキーを選び、最大八件の割り当てをメモリーに保持します。再起動すると記録は失われますが、オブジェクトは削除されません。デプロイするアプリでは、ローカルアクセスコードの代わりに、独自のユーザーセッションと永続的な所有権記録が必要です。
署名付き URL は、所持者が権限を行使でき、有効期限まで再利用できる仕組みです。入手した人は、アプリのアクセスコードなしで使用できます。URL をログ、分析データ、共有メッセージに含めないでください。この例では URL を表示せず、アプリの認証ヘッダーを R2 に転送することもありません。
非公開バケットとローカルプロジェクトの準備
管理下にある、デフォルトの管轄区域の非公開 R2 バケットを使用し、パブリックアクセスを無効にしてください。バケット名、Cloudflare アカウント ID、および対象バケットに範囲を限定した Object Read & Write 権限を持つ R2 S3 アクセスキー ID とシークレットアクセスキーが必要です。Cloudflare の R2 認証ガイド に従って取得してください。Wrangler へのログインや Worker のバケットバインディングでは、S3 キーペアは取得できません。
コマンドは Linux 上の Bash、Node.js 26.12.0(検証済みの Current リリース)、および別途インストールした Corepack 0.36.0 を使用します。Node.js 26 には Corepack が同梱されていません。新規インストールには、保守されている Node.js 26 のパッチ版を使用してください。以下ではパッケージのバージョンを固定し、この例を再現できるようにしています。SDK の固定バージョンは、検証時にプロジェクトの二日間のパッケージ経過日数制限 を満たした最新リリースです。ブラウザーには File API と Web Crypto が必要で、Chromium ではこのループバックオリジンで利用できます。
書き込み可能なディレクトリで、次のブロックを貼り付けてください。新しいプロジェクトを作成しますが、シェルの作業ディレクトリは元のままです。ディレクトリがすでに存在する場合は、上書きせずに停止します。インストールに失敗すると、調査用に新しいディレクトリが残ります。やり直す場合は別の空の場所を選んでください。
(
set -eu
command -v node >/dev/null || { printf 'Install Node.js first.\n' >&2; exit 1; }
command -v corepack >/dev/null || { printf 'Install Corepack first.\n' >&2; exit 1; }
node -e 'if (Number(process.versions.node.split(".")[0]) !== 26) process.exit(1)'
mkdir r2-browser-demo
cd r2-browser-demo
printf '%s\n' '{"private":true,"type":"module","packageManager":"yarn@4.18.1"}' > package.json
printf '%s\n' 'nodeLinker: node-modules' 'enableGlobalCache: false' 'ignorePath: true' 'npmMinimalAgeGate: 2d' > .yarnrc.yml
touch yarn.lock
corepack yarn add --exact @aws-sdk/client-s3@3.1150.0 @aws-sdk/s3-request-presigner@3.1150.0 zod@4.6.7
)
次の三つのファイルを r2-browser-demo 内に保存してください。ローカルの Yarn 設定では、上位プロジェクトが Plug’n’Play を使用していても、通常の node_modules とプロジェクトキャッシュを明示的に選択します。
ブラウザー用 CORS の設定
バケットの設定で、ダッシュボードの JSON エディターを使ってこのポリシーを入力してください。既存のポリシーを置き換えるのは、デモ専用バケットの場合だけにしてください。それ以外では、アプリが必要としている既存のルールにこのルールを追加します。許可するのはローカルサーバーが出力する正確なオリジンであり、すべての localhost 名ではありません。
[
{
"AllowedOrigins": ["http://127.0.0.1:8080"],
"AllowedMethods": ["PUT"],
"AllowedHeaders": ["Content-Type"]
}
]
バケットの CORS は、ブラウザーのクロスオリジン PUT を許可します。アプリに権限を要求するユーザーを認証するものではありません。署名付き URL は CORS を強制しない HTTP クライアントでも使えるため、オリジンの制限はサーバー側の認可の代わりにはなりません。
署名処理とバイト列検証処理の保存
次の内容を storage.mts として保存してください。クライアントは標準の R2 S3 エンドポイントと明示的な認証情報を使い、個人用の AWS 設定を検索しません。ここでは WHEN_REQUIRED で SDK の任意のリクエストチェックサム計算を無効にします。この例では ETag を SHA-256 ダイジェストとみなさず、保存された本文全体を独自に検証します。このチェックサム設定については AWS のドキュメントを参照してください。
// storage.mts
import { randomUUID } from 'node:crypto'
import { S3Client } from '@aws-sdk/client-s3'
import { z } from 'zod'
const parsed = z.object({
CLOUDFLARE_ACCOUNT_ID: z.string().regex(/^[a-f0-9]{32}$/),
R2_BUCKET_NAME: z.string().min(3).max(63),
R2_ACCESS_KEY_ID: z.string().min(1),
R2_SECRET_ACCESS_KEY: z.string().min(1),
UPLOAD_TOKEN: z.string().min(32).max(256),
PORT: z.coerce.number().int().min(1024).max(65535).default(8080),
}).safeParse(process.env)
if (!parsed.success) throw new Error('Set all five configuration values; use a 32+ character access code.')
export const config = parsed.data
export const origin = `http://127.0.0.1:${config.PORT}`
export const prefix = `browser-demo/${randomUUID()}/`
export const maxBytes = 10 * 1024 * 1024
export const r2 = new S3Client({
region: 'auto',
endpoint: `https://${config.CLOUDFLARE_ACCOUNT_ID}.r2.cloudflarestorage.com`,
credentials: {
accessKeyId: config.R2_ACCESS_KEY_ID,
secretAccessKey: config.R2_SECRET_ACCESS_KEY,
},
requestChecksumCalculation: 'WHEN_REQUIRED',
})
次の内容を server.mts として保存してください。ローカルページからの認証済みリクエストだけが、アップロードを割り当てられます。キーも所有者もブラウザーの入力からは取得しません。検証時には同じ所有権記録を使って不透明な ID を解決するため、呼び出し元がサーバーに任意のバケットオブジェクトを読み取らせることはできません。
// server.mts
import { createHash, randomUUID, timingSafeEqual } from 'node:crypto'
import { readFile } from 'node:fs/promises'
import { createServer } from 'node:http'
import type { IncomingMessage, ServerResponse } from 'node:http'
import { GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3'
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
import { z } from 'zod'
import { config, maxBytes, origin, prefix, r2 } from './storage.mts'
const inputSchema = z.object({
size: z.number().int().min(0).max(maxBytes),
sha256: z.string().regex(/^[a-f0-9]{64}$/),
}).strict()
const allocations = new Map<string, { owner: string; key: string; size: number; sha256: string }>()
const page = `<!doctype html><html lang="en"><meta charset="utf-8">
<title>R2 browser upload</title><main><h1>R2 browser upload</h1>
<form><fieldset>
<label>Local access code <input id="accessCode" type="password" autocomplete="off" required></label>
<label>File <input id="file" type="file" required></label>
<button>Upload</button>
</fieldset></form><p role="status" aria-live="polite">Choose a file, including an empty file.</p>
<script type="module" src="/uploader.js"></script></main></html>`
function reply(res: ServerResponse, status: number, body: unknown): void {
res.writeHead(status, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(body))
}
async function json(req: IncomingMessage): Promise<unknown> {
const parts: Buffer[] = []
let length = 0
for await (const part of req) {
length += part.length
if (length > 4096) throw new Error('Request too large')
parts.push(part)
}
return JSON.parse(Buffer.concat(parts).toString('utf8'))
}
async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
res.setHeader('Cache-Control', 'no-store')
res.setHeader('Referrer-Policy', 'no-referrer')
if (req.headers.host !== new URL(origin).host) return reply(res, 403, { error: 'Use the printed local address.' })
if (req.method === 'GET' && req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' })
res.end(page)
return
}
if (req.method === 'GET' && req.url === '/uploader.js') {
res.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8' })
res.end(await readFile(new URL('./uploader.ts', import.meta.url)))
return
}
if (!req.url?.startsWith('/api/')) return reply(res, 404, { error: 'Not found.' })
const supplied = Buffer.from(req.headers.authorization ?? '')
const expected = Buffer.from(`Bearer ${config.UPLOAD_TOKEN}`)
if (supplied.length !== expected.length || !timingSafeEqual(supplied, expected)) {
return reply(res, 401, { error: 'Access code required.' })
}
if (req.headers.origin !== origin) return reply(res, 403, { error: 'Origin refused.' })
const owner = 'local-user'
if (req.method === 'POST' && req.url === '/api/uploads') {
const input = inputSchema.safeParse(await json(req))
if (!input.success) return reply(res, 400, { error: 'Expected size 0–10 MiB and a SHA-256 digest.' })
if (allocations.size >= 8) return reply(res, 429, { error: 'Eight allocations used. Restart for a new session.' })
const id = randomUUID()
const key = `${prefix}${owner}/${id}`
allocations.set(id, { owner, key, ...input.data })
// Log only the opaque key, so failed uploads can be found and removed.
console.info(`Allocated key: ${key}`)
const url = await getSignedUrl(r2, new PutObjectCommand({
Bucket: config.R2_BUCKET_NAME, Key: key, ContentType: 'application/octet-stream',
}), { expiresIn: 120, signableHeaders: new Set(['content-type']) })
return reply(res, 200, { id, key, url })
}
const match = /^\/api\/uploads\/([a-f0-9-]{36})\/verify$/.exec(req.url)
const allocation = match ? allocations.get(match[1]) : undefined
if (req.method !== 'POST' || !allocation || allocation.owner !== owner) {
return reply(res, 404, { error: 'Upload not found in this session.' })
}
const object = await r2.send(new GetObjectCommand({
Bucket: config.R2_BUCKET_NAME, Key: allocation.key,
}))
if (!object.Body) throw new Error('Missing stored body')
const reader = object.Body.transformToWebStream().getReader()
const hash = createHash('sha256')
let size = 0
try {
for (;;) {
const chunk = await reader.read()
if (chunk.done) break
size += chunk.value.length
if (size > maxBytes) return reply(res, 409, { error: 'Stored object exceeds 10 MiB.' })
hash.update(chunk.value)
}
} finally {
await reader.cancel()
reader.releaseLock()
}
const sha256 = hash.digest('hex')
if (size !== allocation.size || sha256 !== allocation.sha256) {
return reply(res, 409, { error: 'Stored bytes differ from the selected file.' })
}
reply(res, 200, { key: allocation.key, bytes: size, sha256 })
}
const server = createServer((req, res) => {
handle(req, res).catch(() => {
console.error('Upload request failed. Check local configuration and R2 access.')
if (!res.headersSent) reply(res, 500, { error: 'Upload request failed.' })
else res.end()
})
})
server.on('error', () => {
console.error('Cannot start the upload server. Check whether the port is already in use.')
r2.destroy()
process.exitCode = 1
})
server.listen(config.PORT, '127.0.0.1', () => console.info(`Open ${origin}`))
for (const signal of ['SIGINT', 'SIGTERM']) {
process.once(signal, () => {
server.close()
server.closeAllConnections()
r2.destroy()
})
}
PUT URL の有効期間は 120 秒で、Content-Type: application/octet-stream を署名対象に含めます。ブラウザーは、その値を正確に送信する必要があります。ここでは意図的に、任意のファイルのバイト列を汎用メディアタイプで保存します。このヘッダーはメタデータであり、ファイル形式や安全性の証拠ではありません。10 MiB のチェックが制限するのはアプリの通常の処理経路と検証処理であり、漏えいした URL の悪意ある所持者が PUT できるサイズではありません。
ブラウザー側アップローダーの保存
次の内容を uploader.ts として保存してください。JavaScript 構文を使うため、ビルド工程なしでサーバーからモジュールとして直接配信できます。最後の読み戻しが終わるまでコントロールは無効のままで、処理中の再送信は無視されます。
// uploader.ts: JavaScript syntax, served directly to the browser.
const form = document.querySelector('form')
const fields = document.querySelector('fieldset')
const accessCode = document.querySelector('#accessCode')
const input = document.querySelector('#file')
const status = document.querySelector('[role="status"]')
if (!(form instanceof HTMLFormElement) || !(fields instanceof HTMLFieldSetElement) ||
!(accessCode instanceof HTMLInputElement) || !(input instanceof HTMLInputElement) ||
!(status instanceof HTMLElement)) throw new Error('Upload controls are missing')
let busy = false
form.addEventListener('submit', async (event) => {
event.preventDefault()
if (busy) return
const file = input.files?.[0]
if (!file) return
if (file.size > 10 * 1024 * 1024) {
status.textContent = 'Choose a file of at most 10 MiB.'
return
}
busy = true
fields.disabled = true
let key = ''
const authorization = `Bearer ${accessCode.value}`
try {
status.textContent = 'Preparing upload…'
const digest = await crypto.subtle.digest('SHA-256', await file.arrayBuffer())
const sha256 = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('')
const permission = await fetch('/api/uploads', {
method: 'POST',
headers: { Authorization: authorization, 'Content-Type': 'application/json' },
body: JSON.stringify({ size: file.size, sha256 }),
})
if (!permission.ok) throw new Error(`Permission refused (${permission.status}).`)
const allocation = await permission.json()
key = allocation.key
status.textContent = 'Uploading…'
const uploaded = await fetch(allocation.url, {
method: 'PUT', body: file, headers: { 'Content-Type': 'application/octet-stream' },
credentials: 'omit', referrerPolicy: 'no-referrer',
})
if (!uploaded.ok) throw new Error(`R2 refused the upload (${uploaded.status}).`)
status.textContent = 'Verifying stored bytes…'
const verification = await fetch(`/api/uploads/${allocation.id}/verify`, {
method: 'POST', headers: { Authorization: authorization },
})
if (!verification.ok) throw new Error('Stored bytes could not be verified.')
const receipt = await verification.json()
if (receipt.key !== key || receipt.bytes !== file.size || receipt.sha256 !== sha256) {
throw new Error('Stored bytes could not be verified.')
}
status.textContent = `Verified ${receipt.bytes.toLocaleString()} bytes. Key: ${key}`
} catch (error) {
const message = error instanceof Error && /^(Permission refused|R2 refused|Stored bytes)/.test(error.message)
? error.message : 'Upload did not complete. Check the connection and bucket CORS.'
status.textContent = `${message}${key ? ` Key: ${key}` : ''}`
} finally {
busy = false
fields.disabled = false
}
})
アプリの起動とファイルのアップロード
セットアップ時と同じ親ディレクトリから、ターミナルに次のブロックを貼り付けてください。秘密情報の入力は非表示になり、サブシェルを使うことで親シェルの環境にも残りません。ページで再入力できる長いローカルアクセスコードを選んでください。R2 の認証情報とは別のものです。
(
set -eu
cd r2-browser-demo
read -r -p 'Cloudflare account ID: ' CLOUDFLARE_ACCOUNT_ID
read -r -p 'R2 bucket name: ' R2_BUCKET_NAME
read -r -s -p 'R2 access key ID: ' R2_ACCESS_KEY_ID; printf '\n'
read -r -s -p 'R2 secret access key: ' R2_SECRET_ACCESS_KEY; printf '\n'
read -r -s -p 'Local access code (32+ characters): ' UPLOAD_TOKEN; printf '\n'
export CLOUDFLARE_ACCOUNT_ID R2_BUCKET_NAME R2_ACCESS_KEY_ID R2_SECRET_ACCESS_KEY UPLOAD_TOKEN
node server.mts
)
http://127.0.0.1:8080 を開き、Local access code にコードを入力し、File でファイルを選び、Upload を選択してください。最終ステータスは Verified で始まり、バイト数とオブジェクトキーを示します。このメッセージは、サーバーが R2 から読み取り、双方が期待されるサイズとダイジェストを確認した後にだけ表示されます。テキストファイル、バイナリファイル、空のファイルで試してください。ファイル名はオブジェクトキーには使用しません。
完了後にクリックするたび、新しい UUID キーが割り当てられます。以前のアップロードは置き換えません。中断されたアップロードも見つけられるように、サーバーは割り当てたキーを出力します。テスト後は、最後の割り当てから少なくとも 120 秒待ち、Ctrl+C でサーバーを停止してから、該当するオブジェクトをバケットから削除してください。サーバーを停止しても、発行済みの URL は失効せず、ファイルも削除されません。
アップロード失敗の診断
401 で権限を拒否された場合は、ローカルアクセスコードを確認してください。400 は署名処理が有効なサイズとダイジェストを受け取っていないことを、429 はこのプロセスが八件の割り当てを使い切ったことを意味します。再起動すると新しいセッションを開始できるため、この上限は範囲を限定したローカルデモ用であり、本番環境のクォータではありません。
ブラウザーのネットワークエラーでは、ブラウザーのネットワークツールで失敗した段階を調べてください。OPTIONS プリフライトの失敗は、バケットで許可したオリジン、メソッド、ヘッダーに問題があることを示します。ポリシーを変更する前に、ポートと 127.0.0.1 の綴りを確認してください。署名の拒否は別の R2 認可エラーです。署名対象のコンテンツタイプを変更すると権限が無効になります。期限切れの URL も拒否され、そのレスポンスには CORS ヘッダーが含まれない場合があるため、ブラウザーの JavaScript ではネットワークエラーしか確認できないことがあります。この違いは Cloudflare の CORS ガイドで説明されています。
検証の失敗は、選択したバイト列をアプリが確認できていないことを意味します。再試行前に割り当てられたキーを調べてください。レスポンスが失敗したり失われたりしても、保存済みオブジェクトが残る場合があります。再試行では新しいキーを作成し、ファイル全体を再送信します。この例は、自動再試行や再開の機能をうたうものではありません。
アプリの次のステップの選択
10 MiB を超えるファイルは、このデモのポリシーの対象外としてください。マルチパートアップロードには、開始、パートの署名、完了、中止を扱う、別の認証付きライフサイクルが必要です。ここでは実装していません。Worker でアプリケーションロジックをホストすることもできますが、このガイドで実行するのはローカルの Node.js 署名サーバーです。署名付き URL は R2 の S3 ホスト名を使用し、カスタムドメインは使用できません。
より高機能なアップロードインターフェイスには、Uppy を検討してください。アップローダーをアプリに接続する場合も、ここで示した所有権と署名の責任範囲を分ける仕組みが必要です。
