Cross-origin resource sharing (CORS) allows interactions between resources
from different origins, something that is normally prohibited in order to
prevent malicious behavior. Use this page to learn how to set a CORS
configuration on a Cloud Storage bucket and how to view the CORS
configuration set on a bucket. See Configuration examples for CORS for
example CORS configurations.
Required roles
To get the permissions that you need to set and view the CORS configuration
on a bucket, ask your administrator to grant you the Storage Admin
(roles/storage.admin) role on the bucket.
This predefined role contains the permissions required to set and view CORS
configurations. To see the exact permissions that are required, expand the
Required permissions section:
You set a CORS configuration on a bucket by specifying information, such as HTTP
methods and originating domains, that identifies the types of requests the bucket
can accept.
Use the following steps to set a CORS configuration on your bucket:
Console
In the Google Cloud console, go to the Cloud Storage Buckets page.
The following sample sets a CORS configuration on a bucket:
usingGoogle.Apis.Storage.v1.Data;usingGoogle.Cloud.Storage.V1;usingSystem;usingSystem.Collections.Generic;usingstaticGoogle.Apis.Storage.v1.Data.Bucket;publicclassBucketAddCorsConfigurationSample{publicBucketBucketAddCorsConfiguration(stringbucketName="your-bucket-name"){varstorage=StorageClient.Create();varbucket=storage.GetBucket(bucketName);CorsDatacorsData=newCorsData{Origin=newstring[]{"*"},ResponseHeader=newstring[]{"Content-Type","x-goog-resumable"},Method=newstring[]{"PUT","POST"},MaxAgeSeconds=3600//One Hour};if(bucket.Cors==null){bucket.Cors=newList<CorsData>();}bucket.Cors.Add(corsData);bucket=storage.UpdateBucket(bucket);Console.WriteLine($"bucketName {bucketName} was updated with a CORS config to allow {string.Join(",", corsData.Method)} requests from"+$" {string.Join(",", corsData.Origin)} sharing {string.Join(",", corsData.ResponseHeader)} responseHeader"+$" responses across origins.");returnbucket;}}
The following sample sets a CORS configuration on a bucket:
import("context""fmt""io""time""cloud.google.com/go/storage")// setBucketCORSConfiguration sets a CORS configuration on a bucket.funcsetBucketCORSConfiguration(wio.Writer,bucketNamestring,maxAgetime.Duration,methods,origins,responseHeaders[]string)error{// bucketName := "bucket-name"// maxAge := time.Hour// methods := []string{"GET"}// origins := []string{"some-origin.com"}// responseHeaders := []string{"Content-Type"}ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*10)defercancel()bucket:=client.Bucket(bucketName)bucketAttrsToUpdate:=storage.BucketAttrsToUpdate{CORS:[]storage.CORS{{MaxAge:maxAge,Methods:methods,Origins:origins,ResponseHeaders:responseHeaders,}},}if_,err:=bucket.Update(ctx,bucketAttrsToUpdate);err!=nil{returnfmt.Errorf("Bucket(%q).Update: %w",bucketName,err)}fmt.Fprintf(w,"Bucket %v was updated with a CORS config to allow %v requests from %v sharing %v responses across origins\n",bucketName,methods,origins,responseHeaders)returnnil}
The following sample sets a CORS configuration on a bucket:
importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.Cors;importcom.google.cloud.storage.HttpMethod;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;importcom.google.common.collect.ImmutableList;publicclassConfigureBucketCors{publicstaticvoidconfigureBucketCors(StringprojectId,StringbucketName,Stringorigin,StringresponseHeader,IntegermaxAgeSeconds){// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";// The origin for this CORS config to allow requests from// String origin = "http://example.appspot.com";// The response header to share across origins// String responseHeader = "Content-Type";// The maximum amount of time the browser can make requests before it must repeat preflighted// requests// Integer maxAgeSeconds = 3600;Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();Bucketbucket=storage.get(bucketName);// See the HttpMethod documentation for other HTTP methods available:// https://cloud.google.com/appengine/docs/standard/java/javadoc/com/google/appengine/api/urlfetch/HTTPMethodHttpMethodmethod=HttpMethod.GET;Corscors=Cors.newBuilder().setOrigins(ImmutableList.of(Cors.Origin.of(origin))).setMethods(ImmutableList.of(method)).setResponseHeaders(ImmutableList.of(responseHeader)).setMaxAgeSeconds(maxAgeSeconds).build();bucket.toBuilder().setCors(ImmutableList.of(cors)).build().update();System.out.println("Bucket "+bucketName+" was updated with a CORS config to allow GET requests from "+origin+" sharing "+responseHeader+" responses across origins");}}
The following sample sets a CORS configuration on a bucket:
// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// The origin for this CORS config to allow requests from// const origin = 'http://example.appspot.com';// The response header to share across origins// const responseHeader = 'Content-Type';// The maximum amount of time the browser can make requests before it must// repeat preflighted requests// const maxAgeSeconds = 3600;// The name of the method// See the HttpMethod documentation for other HTTP methods available:// https://cloud.google.com/appengine/docs/standard/java/javadoc/com/google/appengine/api/urlfetch/HTTPMethod// const method = 'GET';asyncfunctionconfigureBucketCors(){awaitstorage.bucket(bucketName).setCorsConfiguration([{maxAgeSeconds,method:[method],origin:[origin],responseHeader:[responseHeader],},]);console.log(`Bucket ${bucketName} was updated with a CORS config to allow ${method} requests from ${origin} sharing ${responseHeader} responses across origins`);}configureBucketCors().catch(console.error);
The following sample sets a CORS configuration on a bucket:
use Google\Cloud\Storage\StorageClient;/** * Update the CORS configuration of a bucket. * * @param string $bucketName The name of your Cloud Storage bucket. * (e.g. 'my-bucket') * @param string $method The HTTP method for the CORS config. (e.g. 'GET') * @param string $origin The origin from which the CORS config will allow requests. * (e.g. 'http://example.appspot.com') * @param string $responseHeader The response header to share across origins. * (e.g. 'Content-Type') * @param int $maxAgeSeconds The maximum amount of time the browser can make * (e.g. 3600) * requests before it must repeat preflighted requests. */function cors_configuration(string $bucketName, string $method, string $origin, string $responseHeader, int $maxAgeSeconds): void{ $storage = new StorageClient(); $bucket = $storage->bucket($bucketName); $bucket->update([ 'cors' => [ [ 'method' => [$method], 'origin' => [$origin], 'responseHeader' => [$responseHeader], 'maxAgeSeconds' => $maxAgeSeconds, ] ] ]); printf( 'Bucket %s was updated with a CORS config to allow GET requests from ' . '%s sharing %s responses across origins.', $bucketName, $origin, $responseHeader );}
The following sample sets a CORS configuration on a bucket:
fromgoogle.cloudimportstoragedefcors_configuration(bucket_name):"""Set a bucket's CORS policies configuration."""# bucket_name = "your-bucket-name"storage_client=storage.Client()bucket=storage_client.get_bucket(bucket_name)bucket.cors=[{"origin":["*"],"responseHeader":["Content-Type","x-goog-resumable"],"method":['PUT','POST'],"maxAgeSeconds":3600}]bucket.patch()print(f"Set CORS policies for bucket {bucket.name} is {bucket.cors}")returnbucket
The following sample sets a CORS configuration on a bucket:
defcors_configurationbucket_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_namebucket.corsdo|c|c.add_rule["*"],["PUT","POST"],headers:["Content-Type","x-goog-resumable"],max_age:3600endputs"Set CORS policies for bucket #{bucket_name}"end
Rust
The following sample sets a CORS configuration on a bucket:
usegoogle_cloud_storage::client::StorageControl;usegoogle_cloud_storage::model::bucket::Cors;usegoogle_cloud_wkt::FieldMask;pubasyncfnsample(client:&StorageControl,bucket_id:&str)->anyhow::Result<()>{letbucket=client.get_bucket().set_name(format!("projects/_/buckets/{bucket_id}")).send().await?;letmetageneration=bucket.metageneration;letmutcors=bucket.cors.clone();cors.push(Cors::new().set_origin(["http://example.appspot.com".to_string()]).set_method(["GET".to_string(),"HEAD".to_string(),"DELETE".to_string()]).set_response_header(["Content-Type".to_string()]).set_max_age_seconds(3600),);letbucket=client.update_bucket().set_bucket(bucket.set_cors(cors)).set_if_metageneration_match(metageneration).set_update_mask(FieldMask::default().set_paths(["cors"])).send().await?;println!("successfully updated bucket CORS for {bucket_id}: {bucket:?}");Ok(())}
REST APIs
JSON API
Have gcloud CLI installed and initialized, which lets
you generate an access token for the Authorization header.
Where BUCKET_NAME is the name of the bucket
whose CORS configuration you want to view. For example, my-bucket.
Client libraries
To view the CORS configuration for a bucket using the client libraries,
follow the instructions for displaying a bucket's metadata and look for the
CORS field in the response:
importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.BucketInfo;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;importjava.util.Map;publicclassGetBucketMetadata{publicstaticvoidgetBucketMetadata(StringprojectId,StringbucketName){// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();// Select all fields. Fields can be selected individually e.g. Storage.BucketField.NAMEBucketbucket=storage.get(bucketName,Storage.BucketGetOption.fields(Storage.BucketField.values()));// Print bucket metadataSystem.out.println("BucketName: "+bucket.getName());System.out.println("DefaultEventBasedHold: "+bucket.getDefaultEventBasedHold());System.out.println("DefaultKmsKeyName: "+bucket.getDefaultKmsKeyName());System.out.println("Id: "+bucket.getGeneratedId());System.out.println("IndexPage: "+bucket.getIndexPage());System.out.println("Location: "+bucket.getLocation());System.out.println("LocationType: "+bucket.getLocationType());System.out.println("Metageneration: "+bucket.getMetageneration());System.out.println("NotFoundPage: "+bucket.getNotFoundPage());System.out.println("RetentionEffectiveTime: "+bucket.getRetentionEffectiveTime());System.out.println("RetentionPeriod: "+bucket.getRetentionPeriod());System.out.println("RetentionPolicyIsLocked: "+bucket.retentionPolicyIsLocked());System.out.println("RequesterPays: "+bucket.requesterPays());System.out.println("SelfLink: "+bucket.getSelfLink());System.out.println("StorageClass: "+bucket.getStorageClass().name());System.out.println("TimeCreated: "+bucket.getCreateTime());System.out.println("VersioningEnabled: "+bucket.versioningEnabled());System.out.println("ObjectRetention: "+bucket.getObjectRetention());if(bucket.getLabels()!=null){System.out.println("\n\n\nLabels:");for(Map.Entry<String,String>label:bucket.getLabels().entrySet()){System.out.println(label.getKey()+"="+label.getValue());}}if(bucket.getLifecycleRules()!=null){System.out.println("\n\n\nLifecycle Rules:");for(BucketInfo.LifecycleRulerule:bucket.getLifecycleRules()){System.out.println(rule);}}}}
// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctiongetBucketMetadata(){/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// Get Bucket Metadataconst[metadata]=awaitstorage.bucket(bucketName).getMetadata();console.log(JSON.stringify(metadata,null,2));}
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2026-06-09 UTC."],[],[]]