0

I'm right now follow this to write a script in Nodejs to write to Google sheets API. However, It turns out my system is not conducive to setting environment variables for this task. I have the credentials json, and I'd imagine I can just place its contents as a variable in my script, right? The two environment variables this tutorial says to set are

export GCLOUD_PROJECT={project ID of your google project}
export GOOGLE_APPLICATION_CREDENTIALS=./service_account_credentials.json

How can I accomplish what this accomplishes, so my code authenticates WITHOUT setting/changing any env variables?

1 Answer 1

2

Most likely you are using googleapis npm module.

You can also use the keyFile property by specifying the path to the service account credential file via the keyFile property in the GoogleAuth constructor:

const {google} = require('googleapis');

const auth = new google.auth.GoogleAuth({
  keyFile: '/path/to/your-secret-key.json',
  scopes: ['https://www.googleapis.com/auth/cloud-platform'],
}); 

You can also set the auth as a global or service-level option so you don't need to specify it every request. For example, you can set auth as a global option:

const {google} = require('googleapis');

const oauth2Client = new google.auth.OAuth2(
  YOUR_CLIENT_ID,
  YOUR_CLIENT_SECRET,
  YOUR_REDIRECT_URL
);

// set auth as a global default
google.options({
  auth: oauth2Client
});
Instead of setting the option globally, you can also set the authentication client at the service-level:

const {google} = require('googleapis');
const oauth2Client = new google.auth.OAuth2(
  YOUR_CLIENT_ID,
  YOUR_CLIENT_SECRET,
  YOUR_REDIRECT_URL
);

const drive = google.drive({
  version: 'v2',
  auth: oauth2Client
});
Sign up to request clarification or add additional context in comments.

2 Comments

thing is that the credentials JSON doesn't have a client secret. Where do I find this? Mine has the fields "type,""project_id","private_key_id","private_key","client_email","client_id","auth_uri","token_uri","auth_provider_x509_cert_url" and "client_x509_cert_url". Also, I do not want the credentials.json content in another file. This is all done with a service account
What do you mean that you don't want the credentials.json file in another file? Would you care to explain what is exactly what you want to do? This answer does solve your original question, authentication without env variables

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.