GCP — Fix CORS Issue When Fetching an Image From Google Cloud Storage

Didik Mulyadi
3 min readSep 24, 2022
https://i.imgur.com/Xe4I20f.png

Our frontend team has an issue when trying to generate a pdf that contains some images URL. They got a “CORS” issue when trying to generate a pdf.

What’s CORS?

The same-origin policy is a security policy enforced on client-side web applications (like web browsers) to prevent interactions between resources from different origins. While useful for preventing malicious behavior, this security measure also prevents legitimate interactions between known origins.

We have set the bucket to public mode, I think it will solve it but unfortunately not 🥲.

After doing a little bit of research, I found the article to allow cors to our bucket.

The important thing is we can’t set the cors config by console. There are 3 ways there, one of them is by gsutil (a terminal in the browser).

Cloud Storage allows you to set a CORS configuration at the bucket level only. You can set the CORS configuration for a bucket using the gsutil command-line tool, the XML API, or the JSON API. However, the CORS configuration applies only to XML API requests.

How to set a CORS config

1. Open the gsutil

Open gsutil by clicking the icon in the navigation bar.

gsutil location

It will open a terminal on the same page

gsutil

2. Check the bucket CORS config

Just run this command in the gsutil. If there’s a config, it will return your config

gsutil cors get gs://YOUR_BUCKET_NAME
found a cors configuration
no cors configuration

3. Add CORS config

If you want to add a CORS for a specific domain

[
{
"origin": ["https://your-example-website.appspot.com"],
"method": ["GET"],
"responseHeader": ["Content-Type"],
"maxAgeSeconds": 3600
}
]

If you want to add a CORS for all origin

[
{
"origin": ["*"],
"method": ["*"],
"responseHeader": ["*"],
"maxAgeSeconds": 3600
}
]

If you want to remove the CORS config

[]

In this article, I will set the config for all origins. Run this command in your gsutil

gsutil cors set cors.json gs://YOUR_BUCKET_NAME

Finish! Just waiting for the cloud to update your bucket config 🎉

Thank you for reading this article!
Reach me:
Linkedln: https://www.linkedin.com/in/didikmulyadi/

--

--

Didik Mulyadi

👋 Hi, Just call me "Didik", I'm a software engineer with experience over 5 years. Reach me on Linkedln https://www.linkedin.com/in/didikmulyadi/