# Cloud Storage

Date: 2018-09-18

# Scope

Every project in this repo that uploads files to Google Cloud Storage

# Context

When uploading files directly from the browser, we need to get a signed policy that allows us to write in the storage in a specific filepath. The backend must generate this policy by using Cloud Storage API:

import CloudStorage from '@google-cloud/storage'
const storage = new CloudStorage(...)

storage
  .bucket('bucket name')
  .file('file name')
  .getSignedPolicy({
    equals: ['$Content-Type', 'image/jpeg'],
    expires: new Date(),
    contentLengthRange: { min: 0, max: 10000000 },
  })

With this policy, browsers can upload files to the specified bucket/filename. However, there is still a CORS issue. To solve it, every bucket that accepts files from browsers need to be configured once as described in Google Cloud Storage docs.

Using OAuth 2.0 Playground and selecting "Cloud Storage JSON API", we can set the CORS configuration with the following payload (PATCH request):

{
  "cors": [
    {
      "origin": ["https://..."],
      "responseHeader": ["Content-Type"],
      "method": ["GET", "HEAD", "POST"],
      "maxAgeSeconds": 3600
    }
  ]
}

Endpoint for API v1 is https://www.googleapis.com/storage/v1/b/<bucket-name>

Last updated: 12/20/2018, 6:21:53 AM