Set CORS to Google Cloud Storage

Posted: December 06, 2022


gsutil

cat cors-json-file.json

[{"origin": ["https://example.com", "https://api.example.com", "https://www.example.com"],"responseHeader": ["Content-Type"],"method": ["GET", "HEAD"],"maxAgeSeconds": 3600}]

export GCS_BUCKET_NAME=my-example-gcs-bucket

# set cors
gsutil cors set cors-json-file.json gs://${GCS_BUCKET_NAME}

# check
gsutil cors get gs://${GCS_BUCKET_NAME}

terraform

resource "google_storage_bucket" "main" {
  name          = "my-example-gcs-bucket"
  location      = "us-central1"
  storage_class = "STANDARD"

  cors {
    max_age_seconds = 3600
    method          = ["GET", "HEAD"]
    origin          = ["https://example.com", "https://api.example.com", "https://www.example.com"]
    response_header = ["Content-Type"]
  }
}