Mar 14, 2023 • 2 min read
Google Cloud Storage CORS
Introduction
When working with Google Cloud Storage as a backend, you will probably need to amend the CORS setting at some point. CORS stands for Cross Origin Resource Sharing and is invoked from your browser as a security access feature. Typically the HTTP-header will indicate which origin is permitted to be accessed. If you want to work with the web and specifically image files, adding a CORS setting will save you time.
CORS Support
In most cases, an XML endpoint will be used to access information in a storage bucket. XML API will restrict access based on CORS configuration, requiring a CORS configuration to be applied if accessed via a Browser. Cloud Storage supports two XML endpoints for objects
- storage.googleapis.com/[BUCKETNAME]
- [BUCKETNAME].storage.google.com
In both instances, you should prefix the storage object with the above endpoint to access the item.
- Reference: Cloud Storage CORS support
CORS Settings File
On Google Cloud a CORS file can be applied to a storage bucket to indicate how to handle access. The settings file is formatted as JSON and contains information on what is permitted.
-
Create a file named
cors-config.json -
Add the following json to the file:
NODE_TYPE // json[ { "origin": ["*"], "method": ["GET"], "responseHeader": ["Content-Type"], "maxAgeSeconds": 3600 } ]
The above configuration includes the following settings:
| Field | Value | Description |
|---|---|---|
| origin | * | Set to where access can be performed. * represents an ALL wildcard |
| method | GET | Represents the HTTP verb (GET |
| responseHeader | [“Content-Type”] | Apply a content-type to the response |
| maxAgeSeconds | 3600 | The max age in seconds before a pre-flight request is repeated |
Adding the above to a storage bucket will allow a HTTP GET operation to be performed from any domain.
If you wish you can restrict the origin to a specific domain e.g. localhost, richrose.dev if you wish.
Expanding the HTTP Verbs is also allowed to bring the flexibility that other platforms take for granted.
CORS Apply
-
Adding the CORS setting to Cloud Storage is done at the bucket level
NODE_TYPE // bashgsutil cors set cors-config.json gs://[BUCKETNAME] -
You can review the CORS setting for a bucket by doing the following:
NODE_TYPE // bashgsutil cors get gs://[BUCKETNAME]
To learn more about adding CORS settings on Google Cloud use the link below: