How to Put a CDN in Front of Firebase Cloud Storage
A lot of people have been asking if you can put a Content Delivery Network (CDN) like Cloudflare in front of Firebase Cloud Storage. Unfortunately, Firebase doesn't allow custom domains, so there is no easy way to add a CDN.
So officially, no.
In fact, Firebase itself doesn't put a CDN in front of Cloud Storage:
Cloud Storage has no built-in CDN; the less short answer is: when your Cloud Storage is "multi-regional", it means that "hot content" (frequently accessed content) is available on different locations, but that is limited to multi-regional locations, and it applies only to the "jurisdiction" of the location, so, for example, if your project is in "us-central", then your multi-regional Storage will be stored only in the US data centers, so when accessed from Toronto, it will be served from the nearest US datacenter.
But all is not lost. There is a way to add to have both a custom domain and a CDN.
A Work-Around to Add a Custom Domain and Cloudflare to Cloud Storage
Here are the steps to put Cloudflare in front of Firebase Cloud Storage. This assumes you have Cloudflare or a similar CDN like Fastly setup.
- In Cloudflare create a new CNAME pointing your subdomain to
c.storage.googleapis.com.
For example:CNAME images.firerun.io
c.storage.googleapis.com.
- In the Firebase console -> Storage, create a new bucket named the subdomain. In the example above, the bucket name would be "images.firerun.io". This is restriction where only the bucket named the same as the subdomain will work.
- Add a test file, for example: keep-calm.jpg
- Next, give public access to the bucket the Google Console. Note, this is different from Firebase security rules where you should set the security rules to allow externally allow read:
- Go to Storage Management in the Google Console. Select your Firebase project.
- Click on your new bucket (e.g. images.firerun.io) and click on the tab "permissions."
- Click the "Add Members" button.
- Enter New Member as "allUsers" and Role as Cloud Storage -> Storage Legacy Object Reader". The Storage Legacy Object Reader prevents external users from doing a directory listing.
- Click "Save" and accept the warning that this is publicly accessible.
And that is it.
Now go to your subdomain with the file appended. For example: https://images.firerun.io/keep-calm.jpg
If there were issues it might be because you have custom SSL certificates at Cloudflare. Try with just http to see if SSL causes problems.
Thank you for reading. 🙏
About Author
Geoff is co-founder of Ayrshare, an API-first platform to automate your social media posts with a few lines of code.