How can I access files from a Google Cloud Storage bucket from a browser?

Learn how can i access files from a google cloud storage bucket from a browser? with practical examples, diagrams, and best practices. Covers google-cloud-storage development techniques with visual...

Accessing Google Cloud Storage Files from a Browser

Hero image for How can I access files from a Google Cloud Storage bucket from a browser?

Learn how to configure Google Cloud Storage (GCS) buckets and objects for public access, enabling direct file retrieval from web browsers.

Google Cloud Storage (GCS) is a highly scalable and durable object storage service. While it's excellent for backend data storage, many applications require direct browser access to files, such as images, videos, or static website assets. This article will guide you through the necessary steps to make your GCS objects accessible from a web browser, covering public access, signed URLs, and CORS configurations.

Understanding Public Access for GCS Objects

The simplest way to allow browser access to GCS files is to make them publicly readable. This means anyone with the object's URL can view or download it. While convenient, it's crucial to understand the security implications. Public access should only be granted to files that are genuinely intended for public consumption and do not contain sensitive information.

flowchart TD
    A[Browser Request] --> B{"Is Object Public?"}
    B -->|Yes| C[GCS Serves Object]
    B -->|No| D[Access Denied]
    C --> E[Browser Displays/Downloads]
    D --> F[Error Message]

Flowchart of public object access in Google Cloud Storage.

Granting Public Read Access to a Bucket or Object

You can grant public read access at either the bucket level (making all objects in the bucket public) or the individual object level. Granting access at the object level is generally recommended for finer-grained control. This involves adding the allUsers principal with the Storage Object Viewer role.

1. Using the Google Cloud Console

Navigate to the Storage browser in the Google Cloud Console. Select your bucket, then select the object(s) you wish to make public. In the 'Permissions' tab, click 'Add principal'. For 'New principals', enter allUsers. For 'Select a role', choose 'Cloud Storage' > 'Storage Object Viewer'. Save your changes.

2. Using gsutil Command-Line Tool

To make a single object public, use: gsutil acl ch -u AllUsers:R gs://YOUR_BUCKET_NAME/YOUR_OBJECT_NAME. To make an entire bucket publicly readable, use: gsutil acl ch -r -u AllUsers:R gs://YOUR_BUCKET_NAME.

3. Using Client Libraries (e.g., Python)

For programmatic access, use the GCS client libraries. The following Python example demonstrates how to make an object public:

from google.cloud import storage

def make_blob_public(bucket_name, blob_name):
    """Makes a blob publicly accessible."""
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)

    blob.make_public()

    print(f"Blob {blob.name} in bucket {bucket.name} is now public.")

# Example usage:
# make_blob_public("your-bucket-name", "your-object-name")

Accessing Public Objects via URL

Once an object is public, you can access it directly via a URL. There are two primary URL formats:

  1. storage.googleapis.com domain: https://storage.googleapis.com/YOUR_BUCKET_NAME/YOUR_OBJECT_NAME
  2. gcs.appspot.com domain (deprecated for new use cases): https://YOUR_BUCKET_NAME.gcs.appspot.com/YOUR_OBJECT_NAME

The storage.googleapis.com domain is the recommended and most common method for direct access.

https://storage.googleapis.com/my-public-bucket/images/my-photo.jpg

Example URL for a publicly accessible GCS object.

Cross-Origin Resource Sharing (CORS) Configuration

If your web application is hosted on a different domain than your GCS bucket (e.g., your-app.com trying to fetch from storage.googleapis.com), you will encounter Cross-Origin Resource Sharing (CORS) errors. To resolve this, you need to configure CORS policies on your GCS bucket.

[
  {
    "origin": ["http://localhost:3000", "https://your-app.com"],
    "method": ["GET", "HEAD", "DELETE"],
    "responseHeader": ["Content-Type"],
    "maxAgeSeconds": 3600
  }
]

Example CORS configuration JSON for a GCS bucket.

1. Applying CORS Configuration

Save the JSON configuration above (or your customized version) to a file, for example, cors-config.json. Then, apply it to your bucket using gsutil:

gsutil cors set cors-config.json gs://YOUR_BUCKET_NAME

2. Verifying CORS Configuration

You can verify the applied CORS configuration using:

gsutil cors get gs://YOUR_BUCKET_NAME

Using Signed URLs for Temporary Access

For objects that should not be publicly accessible but need temporary browser access (e.g., a download link for a private report), Google Cloud Storage offers signed URLs. A signed URL grants temporary access to a specific resource to anyone who possesses the URL, without requiring them to have Google credentials.

sequenceDiagram
    participant A as Application Server
    participant B as GCS
    participant C as Browser

    C->>A: Request Private File Link
    A->>B: Generate Signed URL (with expiration)
    B-->>A: Signed URL
    A-->>C: Signed URL
    C->>B: Access File using Signed URL
    B-->>C: File Content

Sequence diagram for accessing GCS objects using signed URLs.

from google.cloud import storage
import datetime

def generate_signed_url(bucket_name, blob_name, expiration_seconds=3600):
    """Generates a v4 signed URL for downloading a blob."""
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)

    expiration_time = datetime.timedelta(seconds=expiration_seconds)

    signed_url = blob.generate_signed_url(
        version="v4",
        expiration=expiration_time,
        method="GET"
    )

    print(f"Generated signed URL: {signed_url}")
    return signed_url

# Example usage:
# signed_link = generate_signed_url("your-private-bucket", "reports/sensitive-data.pdf", 300)
# print(f"Share this link for 5 minutes: {signed_link}")

Python code to generate a signed URL for a GCS object.