2

I want to use Google Cloud Storage in NodeJS but authenticate with google-auth-library Specifically: I want to host this on heroku, so I want to keep the secret in an environment variable, not in a file (as I'd have to commit the file to deploy to heroku). Basically what is suggested in the auth library: https://github.com/googleapis/google-auth-library-nodejs#loading-credentials-from-environment-variables

But I can't seem to pass the resulting client to the Storage constructor?

Maxim
  • 4,075
  • 1
  • 14
  • 23
PanMan
  • 1,305
  • 1
  • 10
  • 16

1 Answers1

6

Reading the code [1,2,3,4,5] you should be able to pass in credentials as constructor options:

storageOptions = {
  projectId: 'your-project-id',
  credentials: {
        client_email: 'your-client-email',
        private_key: 'your-private-key'
  }
};
client = new Storage(storageOptions);
David
  • 9,288
  • 1
  • 20
  • 52
  • Thanks, this is what I ended up doing, but it's strange the 2 libraries aren't compatible, I would expect to use the fromJson method from the auth library. – PanMan Dec 12 '18 at 10:26
  • 1
    It's especially funny because under the hood the storage lib does use google-auth-library, it just doesn't provide a way for you to pass in the google-auth-library primatives. Might be worth a [feature request](https://github.com/googleapis/nodejs-storage/issues/new) – David Dec 13 '18 at 01:09
  • 1
    +1 for this approach, dug around the google-auth-library code and the @google-cloud code, can't believe they aren't linked... :( – Sohil Pandya Apr 05 '20 at 17:12
  • 1
    I'd also add that you'll need to do some of this `process.env.PRIVATE_KEY.replace(/\\n/gm, '\n')` in order to get the correctly formatted private_key – Sohil Pandya Apr 05 '20 at 18:56
  • Just wrote something up - https://medium.com/@sohilpandya/authenticating-google-service-account-securely-and-with-heroku-a0fdc9da9138?sk=f89a4a0b8730c2048a1e9426b09b6f89 Hope it helps someone in the future. – Sohil Pandya Apr 05 '20 at 21:33