How to Configure CORS for Google Cloud Storage Buckets
To configure
CORS on a Google Cloud Storage bucket, create a JSON file defining the allowed origins, methods, and headers, then apply it using the gsutil cors set command. This setup enables your bucket to accept cross-origin requests from specified domains.Syntax
The CORS configuration for a Google Cloud Storage bucket is a JSON array of rules. Each rule includes:
- origin: List of allowed domains.
- method: HTTP methods allowed (GET, POST, etc.).
- responseHeader: Headers allowed in the response.
- maxAgeSeconds: How long the browser caches the response.
You apply the configuration using the gsutil cors set [JSON_FILE] gs://[BUCKET_NAME] command.
json
[
{
"origin": ["http://example.com"],
"method": ["GET", "POST"],
"responseHeader": ["Content-Type"],
"maxAgeSeconds": 3600
}
]Example
This example shows how to allow cross-origin GET requests from http://example.com with a 1-hour cache time.
bash
[
{
"origin": ["http://example.com"],
"method": ["GET"],
"responseHeader": ["Content-Type"],
"maxAgeSeconds": 3600
}
]
# Apply the CORS configuration
$ gsutil cors set cors-config.json gs://my-bucketOutput
Setting CORS configuration on gs://my-bucket/...
Common Pitfalls
Common mistakes include:
- Using
*as origin, which is not supported by Google Cloud Storage. - Forgetting to include all needed HTTP methods.
- Not applying the configuration after editing the JSON file.
- Setting incorrect bucket names or file paths.
Always verify your JSON syntax and bucket name before applying.
json
# Wrong: Using wildcard origin
[
{
"origin": ["*"] ,
"method": ["GET"],
"responseHeader": ["Content-Type"],
"maxAgeSeconds": 3600
}
]
# Right: Specify exact origins
[
{
"origin": ["http://example.com"],
"method": ["GET"],
"responseHeader": ["Content-Type"],
"maxAgeSeconds": 3600
}
]Quick Reference
- origin: List domains allowed to access your bucket.
- method: HTTP methods allowed (GET, POST, PUT, DELETE, etc.).
- responseHeader: Headers your client can access.
- maxAgeSeconds: Cache duration for preflight requests.
- Use
gsutil cors setto apply the JSON config.
Key Takeaways
Create a JSON file defining allowed origins, methods, headers, and cache time for CORS.
Apply the CORS settings using the gsutil command targeting your bucket.
Avoid using wildcard (*) for origins; specify exact domains instead.
Include all HTTP methods your application needs in the configuration.
Verify JSON syntax and bucket name before applying changes.