[Overview](https://docs.cloud.google.com/storage/docs/cross-origin)
[Configuration samples](https://docs.cloud.google.com/storage/docs/cors-configurations)

[Cross-origin resource sharing (CORS)](https://docs.cloud.google.com/storage/docs/cross-origin) 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](https://docs.cloud.google.com/storage/docs/cors-configurations) 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:

#### Required permissions

- `storage.buckets.get`
- `storage.buckets.update`

You can also get these permissions with other [predefined roles](https://docs.cloud.google.com/iam/docs/roles-permissions) or
[custom roles](https://docs.cloud.google.com/iam/docs/creating-custom-roles).

For information about granting roles on buckets, see
[Set and manage IAM policies on buckets](https://docs.cloud.google.com/storage/docs/access-control/using-iam-permissions).

## Set the CORS configuration on a bucket

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

1. In the Google Cloud console, go to the Cloud Storage **Buckets** page.  

   [Go to Buckets](https://console.cloud.google.com/storage/browser)
2. Click the name of the bucket.

3. Click the **Configuration** tab.

4. In the **Cross-origin resource sharing** section, click
   **Edit CORS configuration**.

5. Select the **Allow cross-origin resource sharing** checkbox.

6. Click **Add a configuration**, and then do the following:

   1. Provide values for the fields in the configuration:

      - **List of allowed origins**: the origins that you want to allow
        for cross-origin resource sharing with this bucket.

      - **Specify methods**: the HTTP methods that you want to allow for
        cross-origin resource sharing with this bucket.

      - **List of allowed response headers**: the response headers that
        you want to allow for cross-origin resource sharing with this
        bucket.

      - **Cache expiry time**: the number of seconds the browser is
        allowed to make requests before it must repeat the preflight
        request.

      For more information about each field, see
      [Components of a CORS configuration](https://docs.cloud.google.com/storage/docs/cross-origin#cors-components).
   2. Click **Done**.

7. Optional: To add additional configurations, repeat the previous step.

8. Click **Save**.

### Command line

1. Create a JSON file with the [CORS configuration](https://docs.cloud.google.com/storage/docs/cross-origin#cors-components) you would like to
   apply. See [configuration examples](https://docs.cloud.google.com/storage/docs/cors-configurations) for sample JSON files.

2. Use the [`gcloud storage buckets update`](https://docs.cloud.google.com/sdk/gcloud/reference/storage/buckets/update) command with the
   `--cors-file` flag:

   ```
   gcloud storage buckets update gs://BUCKET_NAME --cors-file=CORS_CONFIG_FILE
   ```

   Where:
   - `BUCKET_NAME` is the name of the relevant bucket. For example, `my-bucket`.
   - `CORS_CONFIG_FILE` is the path to the JSON file you created in Step 1.

### Client libraries


### C++


For more information, see the
[Cloud Storage C++ API
reference documentation](https://docs.cloud.google.com/cpp/docs/reference/storage/latest).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).

The following sample sets a CORS configuration on a bucket:

    namespace gcs = ::google::cloud::storage;
    using ::google::cloud::StatusOr;
    [](gcs::Client client, std::string const& bucket_name,
       std::string const& origin) {
      StatusOr<gcs::BucketMetadata> original =
          client.GetBucketMetadata(bucket_name);

      if (!original) throw std::move(original).status();
      std::vector<gcs::CorsEntry> cors_configuration;
      cors_configuration.emplace_back(
          gcs::CorsEntry{3600, {"GET"}, {origin}, {"Content-Type"}});

      StatusOr<gcs::BucketMetadata> patched = client.PatchBucket(
          bucket_name,
          gcs::BucketMetadataPatchBuilder().SetCors(cors_configuration),
          gcs::IfMetagenerationMatch(original->metageneration()));
      if (!patched) throw std::move(patched).status();

      if (patched->cors().empty()) {
        std::cout << "Cors configuration is not set for bucket "
                  << patched->name() << "\n";
        return;
      }

      std::cout << "Cors configuration successfully set for bucket "
                << patched->name() << "\nNew cors configuration: ";
      for (auto const& cors_entry : patched->cors()) {
        std::cout << "\n  " << cors_entry << "\n";
      }
    }

### C#


For more information, see the
[Cloud Storage C# API
reference documentation](https://cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).

The following sample sets a CORS configuration on a bucket:


    using Google.Apis.Storage.v1.Data;
    using https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest/Google.Cloud.Storage.V1.html;
    using System;
    using System.Collections.Generic;
    using static Google.Apis.Storage.v1.Data.Bucket;

    public class BucketAddCorsConfigurationSample
    {
        public Bucket BucketAddCorsConfiguration(string bucketName = "your-bucket-name")
        {
            var storage = https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest/Google.Cloud.Storage.V1.StorageClient.html.https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest/Google.Cloud.Storage.V1.StorageClient.html#Google_Cloud_Storage_V1_StorageClient_Create();
            var bucket = storage.GetBucket(bucketName);

            CorsData corsData = new CorsData
            {
                Origin = new string[] { "*" },
                ResponseHeader = new string[] { "Content-Type", "x-goog-resumable" },
                Method = new string[] { "PUT", "POST" },
                MaxAgeSeconds = 3600 //One Hour
            };

            if (bucket.Cors == null)
            {
                bucket.Cors = new List<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.https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest/Google.Cloud.Storage.V1.UploadObjectOptions.html#Google_Cloud_Storage_V1_UploadObjectOptions_Origin)} sharing {string.Join(",", corsData.ResponseHeader)} responseHeader" +
                $" responses across origins.");
            return bucket;
        }
    }

### Go


For more information, see the
[Cloud Storage Go API
reference documentation](https://pkg.go.dev/cloud.google.com/go/storage).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).

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.
    func setBucketCORSConfiguration(w io.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/storage/latest/index.html#cloud_google_com_go_storage_Writer, bucketName string, maxAge time.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)
    	if err != nil {
    		return fmt.Errorf("storage.NewClient: %w", err)
    	}
    	defer client.Close()

    	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
    	defer cancel()

    	bucket := client.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/storage/latest/index.html#cloud_google_com_go_storage_Client_Bucket(bucketName)
    	bucketAttrsToUpdate := storage.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/storage/latest/index.html#cloud_google_com_go_storage_BucketAttrsToUpdate{
    		CORS: []storage.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/storage/latest/index.html#cloud_google_com_go_storage_CORS{
    			{
    				MaxAge:          maxAge,
    				Methods:         methods,
    				Origins:         origins,
    				ResponseHeaders: responseHeaders,
    			}},
    	}
    	if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
    		return fmt.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)
    	return nil
    }

### Java


For more information, see the
[Cloud Storage Java API
reference documentation](https://cloud.google.com/java/docs/reference/google-cloud-storage/latest/overview).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).

The following sample sets a CORS configuration on a bucket:

    import com.google.cloud.storage.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Bucket.html;
    import com.google.cloud.storage.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Cors.html;
    import com.google.cloud.storage.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.HttpMethod.html;
    import com.google.cloud.storage.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Storage.html;
    import com.google.cloud.storage.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.StorageOptions.html;
    import com.google.common.collect.ImmutableList;

    public class ConfigureBucketCors {
      public static void configureBucketCors(
          String projectId,
          String bucketName,
          String origin,
          String responseHeader,
          Integer maxAgeSeconds) {
        // 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;

        https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Storage.html storage = https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.StorageOptions.html.newBuilder().setProjectId(projectId).build().https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.transfermanager.TransferManagerConfig.html#com_google_cloud_storage_transfermanager_TransferManagerConfig_getService__();
        https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Bucket.html bucket = storage.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Storage.html#com_google_cloud_storage_Storage_get_com_google_cloud_storage_BlobId_(bucketName);

        // See the HttpMethod documentation for other HTTP methods available:
        // https://cloud.google.com/appengine/docs/standard/java/javadoc/com/google/appengine/api/urlfetch/HTTPMethod
        https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.HttpMethod.html method = https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.HttpMethod.html.GET;

        https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Cors.html cors =
            https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Cors.html.newBuilder()
                .https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Cors.Builder.html#com_google_cloud_storage_Cors_Builder_setOrigins_java_lang_Iterable_com_google_cloud_storage_Cors_Origin__(ImmutableList.of(https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Cors.html.Origin.of(origin)))
                .https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Cors.Builder.html#com_google_cloud_storage_Cors_Builder_setMethods_java_lang_Iterable_com_google_cloud_storage_HttpMethod__(ImmutableList.of(method))
                .https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Cors.Builder.html#com_google_cloud_storage_Cors_Builder_setResponseHeaders_java_lang_Iterable_java_lang_String__(ImmutableList.of(responseHeader))
                .https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Cors.Builder.html#com_google_cloud_storage_Cors_Builder_setMaxAgeSeconds_java_lang_Integer_(maxAgeSeconds)
                .build();

        bucket.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Bucket.html#com_google_cloud_storage_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");
      }
    }

### Node.js


For more information, see the
[Cloud Storage Node.js API
reference documentation](https://cloud.google.com/nodejs/docs/reference/storage/latest).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).

The following sample sets a CORS configuration on a bucket:

    // Imports the Google Cloud client library
    const {Storage} = require('https://docs.cloud.google.com/nodejs/docs/reference/storage/latest/overview.html');

    // Creates a client
    const storage = new https://docs.cloud.google.com/nodejs/docs/reference/storage-control/latest/storage-control/protos.google.storage.v2.storage-class.html();

    /**
     * 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';

    async function configureBucketCors() {
      await storage.bucket(bucketName).https://docs.cloud.google.com/nodejs/docs/reference/storage/latest/storage/bucket.html([
        {
          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);

### PHP


For more information, see the
[Cloud Storage PHP API
reference documentation](https://googleapis.github.io/google-cloud-php/#/docs/google-cloud/latest/storage/storageclient).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).

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
        );
    }

### Python


For more information, see the
[Cloud Storage Python API
reference documentation](https://cloud.google.com/python/docs/reference/storage/latest).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).

The following sample sets a CORS configuration on a bucket:

    from google.cloud import https://docs.cloud.google.com/python/docs/reference/storage/latest


    def cors_configuration(bucket_name):
        """Set a bucket's CORS policies configuration."""
        # bucket_name = "your-bucket-name"

        storage_client = https://docs.cloud.google.com/python/docs/reference/storage/latest.https://docs.cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.client.Client.html()
        bucket = storage_client.https://docs.cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.client.Client.html#google_cloud_storage_client_Client_get_bucket(bucket_name)
        bucket.https://docs.cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.bucket.Bucket.html#google_cloud_storage_bucket_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.https://docs.cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.bucket.Bucket.html#google_cloud_storage_bucket_Bucket_cors}")
        return bucket

### Ruby


For more information, see the
[Cloud Storage Ruby API
reference documentation](https://googleapis.dev/ruby/google-cloud-storage/latest/Google/Cloud/Storage.html).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).

The following sample sets a CORS configuration on a bucket:

    def cors_configuration bucket_name:
      # The ID of your GCS bucket
      # bucket_name = "your-unique-bucket-name"

      require "google/cloud/storage"

      storage = Google::Cloud::https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage-control/latest/Google-Cloud-Storage.html.https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage/latest/Google-Cloud-Storage.html
      bucket = storage.bucket bucket_name

      bucket.cors do |c|
        c.https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage/latest/Google-Cloud-Storage-Bucket-Cors.html ["*"],
                   ["PUT", "POST"],
                   headers: [
                     "Content-Type",
                     "x-goog-resumable"
                   ],
                   max_age: 3600
      end

      puts "Set CORS policies for bucket #{bucket_name}"
    end

### Rust

The following sample sets a CORS configuration on a bucket:

    use google_cloud_storage::client::StorageControl;
    use google_cloud_storage::model::bucket::Cors;
    use google_cloud_wkt::FieldMask;

    pub async fn sample(client: &StorageControl, bucket_id: &str) -> anyhow::Result<()> {
        let bucket = client
            .get_bucket()
            .set_name(format!("projects/_/buckets/{bucket_id}"))
            .send()
            .await?;
        let metageneration = bucket.metageneration;
        let mut cors = 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),
        );

        let bucket = 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(())
    }

<br />

### REST APIs

### JSON API

1. Have gcloud CLI [installed and initialized](https://docs.cloud.google.com/sdk/docs/install), which lets
   you generate an access token for the `Authorization` header.

2. Create a JSON file with the [CORS configuration](https://docs.cloud.google.com/storage/docs/cross-origin#cors-components) you would like
   to apply. See [configuration examples](https://docs.cloud.google.com/storage/docs/cors-configurations) for sample JSON files.

3. Use [`cURL`](http://curl.haxx.se/) to call the [JSON API](https://docs.cloud.google.com/storage/docs/json_api) with a
   [`PATCH` Bucket](https://docs.cloud.google.com/storage/docs/json_api/v1/buckets/patch) request:

   ```json
   curl --request PATCH \
    'https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=cors' \
    --header 'Authorization: Bearer $(gcloud auth print-access-token)' \
    --header 'Content-Type: application/json' \
    --data-binary @CORS_CONFIG_FILE
   ```

   Where:
   - `BUCKET_NAME` is the name of the bucket. For example, `my-bucket`.
   - `CORS_CONFIG_FILE` is the path to the JSON file you created in Step 2.

### XML API

1. Have gcloud CLI [installed and initialized](https://docs.cloud.google.com/sdk/docs/install), which lets
   you generate an access token for the `Authorization` header.

2. Create an XML file with the [CORS configuration](https://docs.cloud.google.com/storage/docs/cross-origin#cors-components) you would like
   to apply. See [configuration examples](https://docs.cloud.google.com/storage/docs/cors-configurations) for sample XML files.

3. Use [`cURL`](http://curl.haxx.se/) to call the [XML API](https://docs.cloud.google.com/storage/docs/xml-api/overview) with a
   [`PUT Bucket`](https://docs.cloud.google.com/storage/docs/xml-api/put-bucket-metadata) request scoped to `?cors`:

   ```xml
   curl -X PUT --data-binary @CORS_CONFIG_FILE \
   -H "Authorization: Bearer $(gcloud auth print-access-token)" \
   -H "x-goog-project-id: PROJECT_ID" \
   "https://storage.googleapis.com/BUCKET_NAME?cors"
   ```

   Where:
   - `BUCKET_NAME` is the name of the bucket. For example, `my-bucket`.
   - `PROJECT_ID` is the ID of the project associated with the bucket. For example, `my-project`.
   - `CORS_CONFIG_FILE` is the path to the XML file you created in Step 2.

> [!NOTE]
> **Note:** When creating a CORS configuration, you can [specify multiple origins, headers, and methods](https://docs.cloud.google.com/storage/docs/cross-origin#multiple-origins-methods-headers).

## View the CORS configuration for a bucket

### Console

1. In the Google Cloud console, go to the Cloud Storage **Buckets** page.  

   [Go to Buckets](https://console.cloud.google.com/storage/browser)
2. Click the name of the bucket.

3. Click the **Configuration** tab.

4. In the **Cross-origin resource sharing** section, click
   **Edit CORS configuration**.

5. Click the configuration.

6. Optional: Edit the configuration, or click **Cancel** to close the dialog.

### Command line

> [!NOTE]
> **Note:** To change the output formatting from YAML (default) to another format, see [Filtering and formatting output](https://docs.cloud.google.com/sdk/docs/scripting-gcloud#filtering_and_formatting_output) for instructions.

Use the [`gcloud storage buckets describe`](https://docs.cloud.google.com/sdk/gcloud/reference/storage/buckets/describe) command with the
`--format` flag:

```
gcloud storage buckets describe gs://BUCKET_NAME --format="default(cors_config)"
```

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:


### C++


For more information, see the
[Cloud Storage C++ API
reference documentation](https://docs.cloud.google.com/cpp/docs/reference/storage/latest).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).

    namespace gcs = ::google::cloud::storage;
    using ::google::cloud::StatusOr;
    [](gcs::Client client, std::string const& bucket_name) {
      StatusOr<gcs::BucketMetadata> bucket_metadata =
          client.GetBucketMetadata(bucket_name);
      if (!bucket_metadata) throw std::move(bucket_metadata).status();

      std::cout << "The metadata for bucket " << bucket_metadata->name() << " is "
                << *bucket_metadata << "\n";
    }

### C#


For more information, see the
[Cloud Storage C# API
reference documentation](https://cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).


    using Google.Apis.Storage.v1.Data;
    using https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest/Google.Cloud.Storage.V1.html;
    using System;

    public class GetBucketMetadataSample
    {
        public Bucket GetBucketMetadata(string bucketName = "your-unique-bucket-name")
        {
            var storage = https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest/Google.Cloud.Storage.V1.StorageClient.html.https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest/Google.Cloud.Storage.V1.StorageClient.html#Google_Cloud_Storage_V1_StorageClient_Create();
            var bucket = storage.GetBucket(bucketName, new https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest/Google.Cloud.Storage.V1.GetBucketOptions.html { Projection = https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest/Google.Cloud.Storage.V1.Projection.html.https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest/Google.Cloud.Storage.V1.Projection.html#Google_Cloud_Storage_V1_Projection_Full });
            Console.WriteLine($"Bucket:\t{bucket.Name}");
            Console.WriteLine($"Acl:\t{bucket.https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest/Google.Cloud.Storage.V1.UrlSigner.PostPolicyStandardElement.html#Google_Cloud_Storage_V1_UrlSigner_PostPolicyStandardElement_Acl}");
            Console.WriteLine($"Billing:\t{bucket.Billing}");
            Console.WriteLine($"Cors:\t{bucket.Cors}");
            Console.WriteLine($"DefaultEventBasedHold:\t{bucket.DefaultEventBasedHold}");
            Console.WriteLine($"DefaultObjectAcl:\t{bucket.DefaultObjectAcl}");
            Console.WriteLine($"Encryption:\t{bucket.Encryption}");
            if (bucket.Encryption != null)
            {
                Console.WriteLine($"KmsKeyName:\t{bucket.Encryption.DefaultKmsKeyName}");
            }
            Console.WriteLine($"Id:\t{bucket.Id}");
            Console.WriteLine($"Kind:\t{bucket.Kind}");
            Console.WriteLine($"Lifecycle:\t{bucket.Lifecycle}");
            Console.WriteLine($"Location:\t{bucket.Location}");
            Console.WriteLine($"LocationType:\t{bucket.LocationType}");
            Console.WriteLine($"Logging:\t{bucket.Logging}");
            Console.WriteLine($"Metageneration:\t{bucket.Metageneration}");
            Console.WriteLine($"ObjectRetention:\t{bucket.ObjectRetention}");
            Console.WriteLine($"Owner:\t{bucket.Owner}");
            Console.WriteLine($"ProjectNumber:\t{bucket.ProjectNumber}");
            Console.WriteLine($"RetentionPolicy:\t{bucket.RetentionPolicy}");
            Console.WriteLine($"SelfLink:\t{bucket.SelfLink}");
            Console.WriteLine($"StorageClass:\t{bucket.StorageClass}");
            Console.WriteLine($"TimeCreated:\t{bucket.TimeCreated}");
            Console.WriteLine($"Updated:\t{bucket.Updated}");
            Console.WriteLine($"Versioning:\t{bucket.Versioning}");
            Console.WriteLine($"Website:\t{bucket.Website}");
            Console.WriteLine($"TurboReplication:\t{bucket.Rpo}");
            if (bucket.Labels != null)
            {
                Console.WriteLine("Labels:");
                foreach (var label in bucket.Labels)
                {
                    Console.WriteLine($"{label.https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest/Google.Cloud.Storage.V1.UrlSigner.PostPolicyStandardElement.html#Google_Cloud_Storage_V1_UrlSigner_PostPolicyStandardElement_Key}:\t{label.Value}");
                }
            }
            return bucket;
        }
    }

### Go


For more information, see the
[Cloud Storage Go API
reference documentation](https://pkg.go.dev/cloud.google.com/go/storage).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).

    import (
    	"context"
    	"fmt"
    	"io"
    	"time"

    	"cloud.google.com/go/storage"
    )

    // getBucketMetadata gets the bucket metadata.
    func getBucketMetadata(w io.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/storage/latest/index.html#cloud_google_com_go_storage_Writer, bucketName string) (*storage.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/storage/latest/index.html#cloud_google_com_go_storage_BucketAttrs, error) {
    	// bucketName := "bucket-name"
    	ctx := context.Background()
    	client, err := storage.NewClient(ctx)
    	if err != nil {
    		return nil, fmt.Errorf("storage.NewClient: %w", err)
    	}
    	defer client.Close()

    	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
    	defer cancel()
    	attrs, err := client.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/storage/latest/index.html#cloud_google_com_go_storage_Client_Bucket(bucketName).Attrs(ctx)
    	if err != nil {
    		return nil, fmt.Errorf("Bucket(%q).Attrs: %w", bucketName, err)
    	}
    	fmt.Fprintf(w, "BucketName: %v\n", attrs.Name)
    	fmt.Fprintf(w, "Location: %v\n", attrs.Location)
    	fmt.Fprintf(w, "LocationType: %v\n", attrs.LocationType)
    	fmt.Fprintf(w, "StorageClass: %v\n", attrs.StorageClass)
    	fmt.Fprintf(w, "Turbo replication (RPO): %v\n", attrs.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/storage/latest/index.html#cloud_google_com_go_storage_RPO)
    	fmt.Fprintf(w, "TimeCreated: %v\n", attrs.Created)
    	fmt.Fprintf(w, "Metageneration: %v\n", attrs.MetaGeneration)
    	fmt.Fprintf(w, "PredefinedACL: %v\n", attrs.PredefinedACL)
    	if attrs.Encryption != nil {
    		fmt.Fprintf(w, "DefaultKmsKeyName: %v\n", attrs.Encryption.DefaultKMSKeyName)
    	}
    	if attrs.Website != nil {
    		fmt.Fprintf(w, "IndexPage: %v\n", attrs.Website.MainPageSuffix)
    		fmt.Fprintf(w, "NotFoundPage: %v\n", attrs.Website.NotFoundPage)
    	}
    	fmt.Fprintf(w, "DefaultEventBasedHold: %v\n", attrs.DefaultEventBasedHold)
    	if attrs.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/storage/latest/index.html#cloud_google_com_go_storage_RetentionPolicy != nil {
    		fmt.Fprintf(w, "RetentionEffectiveTime: %v\n", attrs.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/storage/latest/index.html#cloud_google_com_go_storage_RetentionPolicy.EffectiveTime)
    		fmt.Fprintf(w, "RetentionPeriod: %v\n", attrs.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/storage/latest/index.html#cloud_google_com_go_storage_RetentionPolicy.RetentionPeriod)
    		fmt.Fprintf(w, "RetentionPolicyIsLocked: %v\n", attrs.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/storage/latest/index.html#cloud_google_com_go_storage_RetentionPolicy.IsLocked)
    	}
    	fmt.Fprintf(w, "ObjectRetentionMode: %v\n", attrs.ObjectRetentionMode)
    	fmt.Fprintf(w, "RequesterPays: %v\n", attrs.RequesterPays)
    	fmt.Fprintf(w, "VersioningEnabled: %v\n", attrs.VersioningEnabled)
    	if attrs.Logging != nil {
    		fmt.Fprintf(w, "LogBucket: %v\n", attrs.Logging.LogBucket)
    		fmt.Fprintf(w, "LogObjectPrefix: %v\n", attrs.Logging.LogObjectPrefix)
    	}
    	if attrs.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/storage/latest/index.html#cloud_google_com_go_storage_CORS != nil {
    		fmt.Fprintln(w, "CORS:")
    		for _, v := range attrs.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/storage/latest/index.html#cloud_google_com_go_storage_CORS {
    			fmt.Fprintf(w, "\tMaxAge: %v\n", v.MaxAge)
    			fmt.Fprintf(w, "\tMethods: %v\n", v.Methods)
    			fmt.Fprintf(w, "\tOrigins: %v\n", v.Origins)
    			fmt.Fprintf(w, "\tResponseHeaders: %v\n", v.ResponseHeaders)
    		}
    	}
    	if attrs.Labels != nil {
    		fmt.Fprintf(w, "\n\n\nLabels:")
    		for key, value := range attrs.Labels {
    			fmt.Fprintf(w, "\t%v = %v\n", key, value)
    		}
    	}
    	return attrs, nil
    }

### Java


For more information, see the
[Cloud Storage Java API
reference documentation](https://cloud.google.com/java/docs/reference/google-cloud-storage/latest/overview).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).


    import com.google.cloud.storage.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Bucket.html;
    import com.google.cloud.storage.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.BucketInfo.html;
    import com.google.cloud.storage.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Storage.html;
    import com.google.cloud.storage.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.StorageOptions.html;
    import java.util.Map;

    public class GetBucketMetadata {
      public static void getBucketMetadata(String projectId, String bucketName) {
        // The ID of your GCP project
        // String projectId = "your-project-id";

        // The ID of your GCS bucket
        // String bucketName = "your-unique-bucket-name";

        https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Storage.html storage = https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.StorageOptions.html.newBuilder().setProjectId(projectId).build().https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.transfermanager.TransferManagerConfig.html#com_google_cloud_storage_transfermanager_TransferManagerConfig_getService__();

        // Select all fields. Fields can be selected individually e.g. Storage.BucketField.NAME
        https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Bucket.html bucket =
            storage.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Storage.html#com_google_cloud_storage_Storage_get_com_google_cloud_storage_BlobId_(bucketName, Storage.BucketGetOption.fields(Storage.BucketField.values()));

        // Print bucket metadata
        System.out.println("BucketName: " + bucket.getName());
        System.out.println("DefaultEventBasedHold: " + bucket.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.BucketInfo.html#com_google_cloud_storage_BucketInfo_getDefaultEventBasedHold__());
        System.out.println("DefaultKmsKeyName: " + bucket.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.BucketInfo.html#com_google_cloud_storage_BucketInfo_getDefaultKmsKeyName__());
        System.out.println("Id: " + bucket.getGeneratedId());
        System.out.println("IndexPage: " + bucket.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.BucketInfo.html#com_google_cloud_storage_BucketInfo_getIndexPage__());
        System.out.println("Location: " + bucket.getLocation());
        System.out.println("LocationType: " + bucket.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.BucketInfo.html#com_google_cloud_storage_BucketInfo_getLocationType__());
        System.out.println("Metageneration: " + bucket.getMetageneration());
        System.out.println("NotFoundPage: " + bucket.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.BucketInfo.html#com_google_cloud_storage_BucketInfo_getNotFoundPage__());
        System.out.println("RetentionEffectiveTime: " + bucket.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.BucketInfo.html#com_google_cloud_storage_BucketInfo_getRetentionEffectiveTime__());
        System.out.println("RetentionPeriod: " + bucket.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.BucketInfo.html#com_google_cloud_storage_BucketInfo_getRetentionPeriod__());
        System.out.println("RetentionPolicyIsLocked: " + bucket.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.BucketInfo.html#com_google_cloud_storage_BucketInfo_retentionPolicyIsLocked__());
        System.out.println("RequesterPays: " + bucket.requesterPays());
        System.out.println("SelfLink: " + bucket.getSelfLink());
        System.out.println("StorageClass: " + bucket.getStorageClass().https://docs.cloud.google.com/java/docs/reference/google-cloud-nio/latest/com.google.cloud.storage.contrib.nio.CloudStorageFileAttributeView.html#com_google_cloud_storage_contrib_nio_CloudStorageFileAttributeView_name__());
        System.out.println("TimeCreated: " + bucket.getCreateTime());
        System.out.println("VersioningEnabled: " + bucket.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.BucketInfo.html#com_google_cloud_storage_BucketInfo_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.LifecycleRule rule : bucket.getLifecycleRules()) {
            System.out.println(rule);
          }
        }
      }
    }

### Node.js


For more information, see the
[Cloud Storage Node.js API
reference documentation](https://cloud.google.com/nodejs/docs/reference/storage/latest).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).

    // Imports the Google Cloud client library
    const {Storage} = require('https://docs.cloud.google.com/nodejs/docs/reference/storage/latest/overview.html');

    // Creates a client
    const storage = new https://docs.cloud.google.com/nodejs/docs/reference/storage-control/latest/storage-control/protos.google.storage.v2.storage-class.html();

    async function getBucketMetadata() {
      /**
       * TODO(developer): Uncomment the following lines before running the sample.
       */
      // The ID of your GCS bucket
      // const bucketName = 'your-unique-bucket-name';

      // Get Bucket Metadata
      const [metadata] = await storage.bucket(bucketName).getMetadata();

      console.log(https://docs.cloud.google.com/nodejs/docs/reference/storage-transfer/latest/storage-transfer/protos.google.storagetransfer.v1.notificationconfig.payloadformat.html.stringify(metadata, null, 2));
    }

### PHP


For more information, see the
[Cloud Storage PHP API
reference documentation](https://googleapis.github.io/google-cloud-php/#/docs/google-cloud/latest/storage/storageclient).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).

    use Google\Cloud\Storage\StorageClient;

    /**
     * Get bucket metadata.
     *
     * @param string $bucketName The name of your Cloud Storage bucket.
     *        (e.g. 'my-bucket')
     */
    function get_bucket_metadata(string $bucketName): void
    {
        $storage = new StorageClient();
        $bucket = $storage->bucket($bucketName);
        $info = $bucket->info();

        printf('Bucket Metadata: %s' . PHP_EOL, print_r($info, true));
    }

### Python


For more information, see the
[Cloud Storage Python API
reference documentation](https://cloud.google.com/python/docs/reference/storage/latest).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).


    from google.cloud import https://docs.cloud.google.com/python/docs/reference/storage/latest


    def bucket_metadata(bucket_name):
        """Prints out a bucket's metadata."""
        # bucket_name = 'your-bucket-name'

        storage_client = https://docs.cloud.google.com/python/docs/reference/storage/latest.https://docs.cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.client.Client.html()
        bucket = storage_client.https://docs.cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.client.Client.html#google_cloud_storage_client_Client_get_bucket(bucket_name)

        print(f"ID: {bucket.id}")
        print(f"Name: {bucket.name}")
        print(f"Storage Class: {bucket.storage_class}")
        print(f"Location: {bucket.https://docs.cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.bucket.Bucket.html#google_cloud_storage_bucket_Bucket_location}")
        print(f"Location Type: {bucket.https://docs.cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.bucket.Bucket.html#google_cloud_storage_bucket_Bucket_location_type}")
        print(f"Cors: {bucket.https://docs.cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.bucket.Bucket.html#google_cloud_storage_bucket_Bucket_cors}")
        print(f"Default Event Based Hold: {bucket.https://docs.cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.bucket.Bucket.html#google_cloud_storage_bucket_Bucket_default_event_based_hold}")
        print(f"Default KMS Key Name: {bucket.default_kms_key_name}")
        print(f"Metageneration: {bucket.metageneration}")
        print(
            f"Public Access Prevention: {bucket.https://docs.cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.bucket.Bucket.html#google_cloud_storage_bucket_Bucket_iam_configuration.https://docs.cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.bucket.IAMConfiguration.html#google_cloud_storage_bucket_IAMConfiguration_public_access_prevention}"
        )
        print(f"Retention Effective Time: {bucket.https://docs.cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.bucket.Bucket.html#google_cloud_storage_bucket_Bucket_retention_policy_effective_time}")
        print(f"Retention Period: {bucket.https://docs.cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.bucket.Bucket.html#google_cloud_storage_bucket_Bucket_retention_period}")
        print(f"Retention Policy Locked: {bucket.https://docs.cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.bucket.Bucket.html#google_cloud_storage_bucket_Bucket_retention_policy_locked}")
        print(f"Object Retention Mode: {bucket.https://docs.cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.bucket.Bucket.html#google_cloud_storage_bucket_Bucket_object_retention_mode}")
        print(f"Requester Pays: {bucket.https://docs.cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.bucket.Bucket.html#google_cloud_storage_bucket_Bucket_requester_pays}")
        print(f"Self Link: {bucket.self_link}")
        print(f"Time Created: {bucket.time_created}")
        print(f"Versioning Enabled: {bucket.https://docs.cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.bucket.Bucket.html#google_cloud_storage_bucket_Bucket_versioning_enabled}")
        print(f"Labels: {bucket.https://docs.cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.bucket.Bucket.html#google_cloud_storage_bucket_Bucket_labels}")

### Ruby


For more information, see the
[Cloud Storage Ruby API
reference documentation](https://googleapis.dev/ruby/google-cloud-storage/latest/Google/Cloud/Storage.html).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).

    def get_bucket_metadata bucket_name:
      # The ID of your GCS bucket
      # bucket_name = "your-unique-bucket-name"

      require "google/cloud/storage"

      storage = Google::Cloud::https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage-control/latest/Google-Cloud-Storage.html.https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage/latest/Google-Cloud-Storage.html
      bucket  = storage.bucket bucket_name

      puts "ID:                       #{bucket.id}"
      puts "Name:                     #{bucket.name}"
      puts "Storage Class:            #{bucket.storage_class}"
      puts "Location:                 #{bucket.location}"
      puts "Location Type:            #{bucket.location_type}"
      puts "Cors:                     #{bucket.cors}"
      puts "Default Event Based Hold: #{bucket.https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage/latest/Google-Cloud-Storage-Bucket.html}"
      puts "Default KMS Key Name:     #{bucket.https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage/latest/Google-Cloud-Storage-Bucket.html}"
      puts "Logging Bucket:           #{bucket.https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage/latest/Google-Cloud-Storage-Bucket.html}"
      puts "Logging Prefix:           #{bucket.https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage/latest/Google-Cloud-Storage-Bucket.html}"
      puts "Metageneration:           #{bucket.metageneration}"
      puts "Retention Effective Time: #{bucket.https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage/latest/Google-Cloud-Storage-Bucket.html}"
      puts "Retention Period:         #{bucket.https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage/latest/Google-Cloud-Storage-Bucket.html}"
      puts "Retention Policy Locked:  #{bucket.https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage/latest/Google-Cloud-Storage-Bucket.html}"
      puts "Requester Pays:           #{bucket.https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage/latest/Google-Cloud-Storage-Bucket.html}"
      puts "Self Link:                #{bucket.api_url}"
      puts "Time Created:             #{bucket.created_at}"
      puts "Versioning Enabled:       #{bucket.https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage/latest/Google-Cloud-Storage-Bucket.html}"
      puts "Index Page:               #{bucket.https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage/latest/Google-Cloud-Storage-Bucket.html}"
      puts "Not Found Page:           #{bucket.https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage/latest/Google-Cloud-Storage-Bucket.html}"
      puts "Labels:"
      bucket.labels.https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage/latest/Google-Cloud-Storage-Policy-Bindings.html do |key, value|
        puts " - #{key} = #{value}"
      end
      puts "Lifecycle Rules:"
      bucket.lifecycle.https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage/latest/Google-Cloud-Storage-Policy-Bindings.html do |rule|
        puts "#{rule.https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage/latest/Google-Cloud-Storage-Bucket-Lifecycle-Rule.html} - #{rule.storage_class} - #{rule.https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage/latest/Google-Cloud-Storage-Bucket-Lifecycle-Rule.html} - #{rule.https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage/latest/Google-Cloud-Storage-Bucket-Lifecycle-Rule.html}"
      end
    end

### Rust

    use google_cloud_storage::client::StorageControl;

    pub async fn sample(client: &StorageControl, bucket_id: &str) -> anyhow::Result<()> {
        let bucket = client
            .get_bucket()
            .set_name(format!("projects/_/buckets/{bucket_id}"))
            .send()
            .await?;
        println!("successfully obtained bucket metadata {bucket:?}");
        Ok(())
    }

<br />

### REST APIs

### JSON API

1. Have gcloud CLI [installed and initialized](https://docs.cloud.google.com/sdk/docs/install), which lets
   you generate an access token for the `Authorization` header.

2. Use [`cURL`](http://curl.haxx.se/) to call the [JSON API](https://docs.cloud.google.com/storage/docs/json_api) with a
   [`GET` Bucket](https://docs.cloud.google.com/storage/docs/json_api/v1/buckets/get) request:

   ```json
   curl -X GET \
       -H "Authorization: Bearer $(gcloud auth print-access-token)" \
       "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=cors"
   ```

   Where `BUCKET_NAME` is the name of the
   bucket whose CORS configuration you want to view. For example,
   `my-bucket`.

### XML API

1. Have gcloud CLI [installed and initialized](https://docs.cloud.google.com/sdk/docs/install), which lets
   you generate an access token for the `Authorization` header.

2. Use [`cURL`](http://curl.haxx.se/) to call the [XML API](https://docs.cloud.google.com/storage/docs/xml-api/overview) with a
   [`GET` Bucket](https://docs.cloud.google.com/storage/docs/xml-api/get-bucket-metadata) request scoped to `?cors`:

   ```xml
   curl -X GET \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     "https://storage.googleapis.com/BUCKET_NAME?cors"
   ```

   Where `BUCKET_NAME` is the name of the
   bucket whose CORS configuration you want to view. For example,
   `my-bucket`.

## Remove the CORS configuration from a bucket

### Console

1. In the Google Cloud console, go to the Cloud Storage **Buckets** page.  

   [Go to Buckets](https://console.cloud.google.com/storage/browser)
2. Click the name of the bucket.

3. Click the **Configuration** tab.

4. In the **Cross-origin resource sharing** section, click
   **Edit CORS configuration**.

5. Do either of the following things:

   - To delete a specific CORS configuration, click
     **Delete** for the
     configuration that you want to remove.

   - To turn off CORS and delete all CORS configurations for the bucket, clear
     the **Allow cross-origin resource sharing** checkbox.

6. Click **Save**.

### Command line

To remove the CORS configuration from a bucket, use the
[`gcloud storage buckets update`](https://docs.cloud.google.com/sdk/gcloud/reference/storage/buckets/update) command with the
`--clear-cors` flag:

```
gcloud storage buckets update gs://BUCKET_NAME --clear-cors
```

Replace <var translate="no">BUCKET_NAME</var> with the name of the bucket whose CORS
configuration you want to remove.

### Client libraries


### C++


For more information, see the
[Cloud Storage C++ API
reference documentation](https://docs.cloud.google.com/cpp/docs/reference/storage/latest).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).

The following sample removes any existing CORS configuration from a bucket:

    namespace gcs = ::google::cloud::storage;
    using ::google::cloud::StatusOr;
    [](gcs::Client client, std::string const& bucket_name) {
      StatusOr<gcs::BucketMetadata> original =
          client.GetBucketMetadata(bucket_name);
      if (!original) throw std::move(original).status();

      StatusOr<gcs::BucketMetadata> patched = client.PatchBucket(
          bucket_name, gcs::BucketMetadataPatchBuilder().ResetCors(),
          gcs::IfMetagenerationMatch(original->metageneration()));
      if (!patched) throw std::move(patched).status();

      std::cout << "Cors configuration successfully removed for bucket "
                << patched->name() << "\n";
    }

### C#


For more information, see the
[Cloud Storage C# API
reference documentation](https://cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).

The following sample removes any existing CORS configuration from a bucket:


    using Google.Apis.Storage.v1.Data;
    using https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest/Google.Cloud.Storage.V1.html;
    using System;

    public class BucketRemoveCorsConfigurationSample
    {
    	public Bucket BucketRemoveCorsConfiguration(string bucketName = "your-bucket-name")
    	{
            var storage = https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest/Google.Cloud.Storage.V1.StorageClient.html.https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.Storage.V1/latest/Google.Cloud.Storage.V1.StorageClient.html#Google_Cloud_Storage_V1_StorageClient_Create();
            var bucket = storage.GetBucket(bucketName);

            if (bucket.Cors == null)
            {
                Console.WriteLine("No CORS to remove");
            }
            else
            {
                bucket.Cors = null;
                bucket = storage.UpdateBucket(bucket);
                Console.WriteLine($"Removed CORS configuration from bucket {bucketName}.");
            }

            return bucket;
    	}
    }

### Go


For more information, see the
[Cloud Storage Go API
reference documentation](https://pkg.go.dev/cloud.google.com/go/storage).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).

The following sample removes any existing CORS configuration from a bucket:

    import (
    	"context"
    	"fmt"
    	"io"
    	"time"

    	"cloud.google.com/go/storage"
    )

    // removeBucketCORSConfiguration removes the CORS configuration from a bucket.
    func removeBucketCORSConfiguration(w io.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/storage/latest/index.html#cloud_google_com_go_storage_Writer, bucketName string) error {
    	// bucketName := "bucket-name"
    	ctx := context.Background()
    	client, err := storage.NewClient(ctx)
    	if err != nil {
    		return fmt.Errorf("storage.NewClient: %w", err)
    	}
    	defer client.Close()

    	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
    	defer cancel()

    	bucket := client.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/storage/latest/index.html#cloud_google_com_go_storage_Client_Bucket(bucketName)
    	bucketAttrsToUpdate := storage.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/storage/latest/index.html#cloud_google_com_go_storage_BucketAttrsToUpdate{
    		CORS: []storage.https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/storage/latest/index.html#cloud_google_com_go_storage_CORS{},
    	}
    	if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
    		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
    	}
    	fmt.Fprintf(w, "Removed CORS configuration from a bucket %v\n", bucketName)
    	return nil
    }

### Java


For more information, see the
[Cloud Storage Java API
reference documentation](https://cloud.google.com/java/docs/reference/google-cloud-storage/latest/overview).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).

The following sample removes any existing CORS configuration from a bucket:


    import com.google.cloud.storage.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Bucket.html;
    import com.google.cloud.storage.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Cors.html;
    import com.google.cloud.storage.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Storage.html;
    import com.google.cloud.storage.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.StorageOptions.html;
    import java.util.ArrayList;
    import java.util.List;

    public class RemoveBucketCors {
      public static void removeBucketCors(String projectId, String bucketName) {
        // The ID of your GCP project
        // String projectId = "your-project-id";

        // The ID of your GCS bucket
        // String bucketName = "your-unique-bucket-name";

        https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Storage.html storage = https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.StorageOptions.html.newBuilder().setProjectId(projectId).build().https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.transfermanager.TransferManagerConfig.html#com_google_cloud_storage_transfermanager_TransferManagerConfig_getService__();
        https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Bucket.html bucket =
            storage.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Storage.html#com_google_cloud_storage_Storage_get_com_google_cloud_storage_BlobId_(bucketName, Storage.BucketGetOption.fields(Storage.BucketField.CORS));

        // getCors() returns the List and copying over to an ArrayList so it's mutable.
        List<Cors> cors = new ArrayList<>(bucket.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.BucketInfo.html#com_google_cloud_storage_BucketInfo_getCors__());

        // Clear bucket CORS configuration.
        cors.clear();

        // Update bucket to remove CORS.
        bucket.https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.cloud.storage.Bucket.html#com_google_cloud_storage_Bucket_toBuilder__().setCors(cors).build().update();
        System.out.println("Removed CORS configuration from bucket " + bucketName);
      }
    }

### Node.js


For more information, see the
[Cloud Storage Node.js API
reference documentation](https://cloud.google.com/nodejs/docs/reference/storage/latest).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).

The following sample removes any existing CORS configuration from a bucket:

    /**
     * TODO(developer): Uncomment the following lines before running the sample.
     */
    // The ID of your GCS bucket
    // const bucketName = 'your-unique-bucket-name';

    // Imports the Google Cloud client library
    const {Storage} = require('https://docs.cloud.google.com/nodejs/docs/reference/storage/latest/overview.html');

    // Creates a client
    const storage = new https://docs.cloud.google.com/nodejs/docs/reference/storage-control/latest/storage-control/protos.google.storage.v2.storage-class.html();

    async function removeBucketCors() {
      await storage.bucket(bucketName).https://docs.cloud.google.com/nodejs/docs/reference/storage/latest/storage/bucket.html([]);

      console.log(`Removed CORS configuration from bucket ${bucketName}`);
    }

    removeBucketCors().catch(console.error);

### PHP


For more information, see the
[Cloud Storage PHP API
reference documentation](https://googleapis.github.io/google-cloud-php/#/docs/google-cloud/latest/storage/storageclient).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).

The following sample removes any existing CORS configuration from a bucket:

    use Google\Cloud\Storage\StorageClient;

    /**
     * Remove the CORS configuration from the specified bucket.
     *
     * @param string $bucketName The name of your Cloud Storage bucket.
     *        (e.g. 'my-bucket')
     */
    function remove_cors_configuration(string $bucketName): void
    {
        $storage = new StorageClient();
        $bucket = $storage->bucket($bucketName);

        $bucket->update([
            'cors' => null,
        ]);

        printf('Removed CORS configuration from bucket %s', $bucketName);
    }

### Python


For more information, see the
[Cloud Storage Python API
reference documentation](https://cloud.google.com/python/docs/reference/storage/latest).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).

The following sample removes any existing CORS configuration from a bucket:

    from google.cloud import https://docs.cloud.google.com/python/docs/reference/storage/latest


    def remove_cors_configuration(bucket_name):
        """Remove a bucket's CORS policies configuration."""
        # bucket_name = "your-bucket-name"

        storage_client = https://docs.cloud.google.com/python/docs/reference/storage/latest.https://docs.cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.client.Client.html()
        bucket = storage_client.https://docs.cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.client.Client.html#google_cloud_storage_client_Client_get_bucket(bucket_name)
        bucket.https://docs.cloud.google.com/python/docs/reference/storage/latest/google.cloud.storage.bucket.Bucket.html#google_cloud_storage_bucket_Bucket_cors = []
        bucket.patch()

        print(f"Remove CORS policies for bucket {bucket.name}.")
        return bucket

### Ruby


For more information, see the
[Cloud Storage Ruby API
reference documentation](https://googleapis.dev/ruby/google-cloud-storage/latest/Google/Cloud/Storage.html).


To authenticate to Cloud Storage, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/storage/docs/authentication#client-libs).

The following sample removes any existing CORS configuration from a bucket:

    def remove_cors_configuration bucket_name:
      # The ID of your GCS bucket
      # bucket_name = "your-unique-bucket-name"

      require "google/cloud/storage"

      storage = Google::Cloud::https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage-control/latest/Google-Cloud-Storage.html.https://docs.cloud.google.com/ruby/docs/reference/google-cloud-storage/latest/Google-Cloud-Storage.html
      bucket = storage.bucket bucket_name

      bucket.cors do |c|
        c.clear
      end

      puts "Remove CORS policies for bucket #{bucket_name}"
    end

### Rust

The following sample removes any existing CORS configuration from a bucket:

    use google_cloud_storage::client::StorageControl;
    use google_cloud_storage::model::bucket::Cors;
    use google_cloud_wkt::FieldMask;

    pub async fn sample(client: &StorageControl, bucket_id: &str) -> anyhow::Result<()> {
        let bucket = client
            .get_bucket()
            .set_name(format!("projects/_/buckets/{bucket_id}"))
            .send()
            .await?;
        let metageneration = bucket.metageneration;

        let bucket = client
            .update_bucket()
            .set_bucket(bucket.set_cors(Vec::<Cors>::new()))
            .set_if_metageneration_match(metageneration)
            .set_update_mask(FieldMask::default().set_paths(["cors"]))
            .send()
            .await?;
        println!(
            "successfully removed CORS rule for bucket {bucket_id}: {:?}",
            bucket.cors
        );
        Ok(())
    }

<br />

### REST APIs

### JSON API

To remove all CORS settings from a bucket, [set](https://docs.cloud.google.com/storage/docs/using-cors#configure-cors-bucket) an empty CORS
configuration on the bucket.

```json
{
  "cors": []
}
```

### XML API

To remove all CORS settings from a bucket, [set](https://docs.cloud.google.com/storage/docs/using-cors#configure-cors-bucket) an empty CORS
configuration on the bucket.

```xml
<CorsConfig></CorsConfig>
```

## What's next

- Explore [CORS configuration examples](https://docs.cloud.google.com/storage/docs/cors-configurations).
- Learn more about [CORS](https://docs.cloud.google.com/storage/docs/cross-origin).
- Learn how to [troubleshoot CORS requests](https://docs.cloud.google.com/storage/docs/troubleshooting#access-bucket-with-cors).