The documentation for the NodeJS Google Auth Library actually provides a complete example on how to load credentials from environment variables. Specifically, it says this approach is recommended when using Heroku-like systems, so I think you should definitely have a look at it.
Once you download the credentials for your service account, with the format below, you can use them by following these steps:
- Load the environment variable using
process.env['NAME_OF_YOUR_ENV_VAR'];
- Parse variable as JSON with
JSON.parse(keysVar);
- Authorize the requests with the keys using the
GoogleAuth.fromJSON()
method.
Credentials format:
$ export CREDS='{
"type": "service_account",
"project_id": "your-project-id",
"private_key_id": "your-private-key-id",
"private_key": "your-private-key",
"client_email": "your-client-email",
"client_id": "your-client-id",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "your-cert-url"
}'
You can find a more detailed example on how to use them in the Google Auth documentation I shared in the second link (or also directly here in this example file), so feel free to adapt it to your use case as convenient.