Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Google Cloud Throwing Error : Could not load the default credentials in Nodejs

I have store this service account key (my-key.json) file in my downloads folder (ubuntu) and then i run this command into my console

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json"

according to google cloud. Now i am running this code but it throws me error.

const language = require('@google-cloud/language');

const quickstart = async function () {
  // Instantiates a client
  const client = new language.LanguageServiceClient();
  // The text to analyze
  const text = 'Hello, world!';
  const document = {
    content: text,
    type: 'PLAIN_TEXT',
  // Detects the sentiment of the text
  const [result] = await client.analyzeSentiment({document: document});
  const sentiment = result.documentSentiment;
  console.log(`Text: ${text}`);
  console.log(`Sentiment score: ${sentiment.score}`);
  console.log(`Sentiment magnitude: ${sentiment.magnitude}`);

**ERORR** -
(node:13928) UnhandledPromiseRejectionWarning: Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
    at GoogleAuth.getApplicationDefaultAsync (/home/hardy/Documents/personal/project/node_modules/google-auth-library/build/src/auth/googleauth.js:154:19)
    at processTicksAndRejections (internal/process/task_queues.js:94:5)
    at async GoogleAuth.getClient (/home/hardy/Documents/personal/project/node_modules/google-auth-library/build/src/auth/googleauth.js:485:17)
    at async GrpcClient._getCredentials (/home/hardy/Documents/personal/project/node_modules/google-gax/build/src/grpc.js:88:24)
    at async GrpcClient.createStub (/home/hardy/Documents/personal/project/node_modules/google-gax/build/src/grpc.js:213:23)

like image 721
hardy Avatar asked Jan 25 '23 05:01


1 Answers

If you are using node <file-name>.js to initialize your code, you should update the command to

GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json" node <file-name>.js

This will make the GOOGLE_APPLICATION_CREDENTIALS available inside your node-environment.

However, as a long-term solution, I would suggest creating a .env file and storing the GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json" in that file.

And then using the dotenv package at the beginning of your js file in the following manner:


You can also refer to https://stackoverflow.com/a/27090755/7743705 for understanding how to set environment variables in pacakge.json.

like image 126
Dhruv Shah Avatar answered Feb 04 '23 18:02

Dhruv Shah