Skip to content
On this page

Setting CORS settings for Cloudflare R2 bucket using API

Setting CORS(Cross-Origin Resource Sharing) settings for a cloudflare r2 bucket. This is required for the bucket to be accessed from a different domain.

API key requires permissions

account -> workers r2 storage -> edit

Using curl here(because I was trying out zx), but fetch should be used if in js.

See also - Mapping a custom domain to Cloudflare R2 bucket using API

typescript
import { $ } from 'zx'

const $$ = $({
    verbose: true,
    env: {
        // NODE_ENV: 'production'
    },
})

const bucket = 'test-bucket'
const accountId = 'xxxxx'

const corsSettings = {"rules":[{
    "allowed": {
        "origins": [`https://example.com`],
        "methods": ["GET", "PUT"],
}}]}

const corsUrl = `https://api.cloudflare.com/client/v4/accounts/${accountId}/r2/buckets/${bucket}/cors`
const corsFlags = [
    '-H', 'accept: */*',
    '-H', 'accept-language: en-US,en;q=0.9',
    '-H', 'content-type: application/json',
    '-X', 'PUT',
    '-H', 'Authorization: Bearer ' + process.env['CLOUDFLARE_API_TOKEN'],
    '--data-raw', JSON.stringify(corsSettings),
]
const corsUpdate = JSON.parse((await $$`curl ${corsUrl} ${corsFlags}`.catch(e => {
    console.error(e.message)
    console.error('-------------------------------------------')
    console.error(`UNKNOWN ERROR - Failed to update CORS settings, they must be added manually`)
    return {stdout: '{}'}
})).stdout)
if(!corsUpdate.success) {
    console.error('-------------------------------------------')
    console.error('\n')
    console.error('Failed to update CORS settings')
    console.error('This must be done manually')
    console.error(`Here - https://dash.cloudflare.com/${accountId}/r2/default/buckets/${bucket}/settings`)
    console.error('Settings - ')
    console.error(JSON.stringify(corsSettings, null, 2))
    console.error('\n')
    console.error('-------------------------------------------')
}
// console.log(corsUpdate)

Made with ❤️ using the awesome vitepress