Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up environment variables in node, specifically, GOOGLE_APPLICATION_CREDENTIALS

I have a node application and I'm trying to use the google language api. I want to set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the json file in the same directory (sibling to package.json and app.js).

I had tried process.env.GOOGLE_APPLICATION_CREDENTIALS = "./key.json"; in my app.js file (using express), but it isn't working. I have also tried putting "GOOGLE_APPLICATION_CREDENTIALS":"./key.json" in my package.json and that didn't work as well. It DOES work when I run in the terminal export GOOGLE_APPLICATION_CREDENTIALS="./key".

Here is the error message:

ERROR: Error: Unexpected error while acquiring application default credentials: Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentials for more information.

Any tips are appreciated, thanks!

like image 300
Ron I Avatar asked Jun 23 '18 22:06

Ron I


People also ask

What is .env file in node?

The dotenv package for handling environment variables is the most popular option in the Node. js community. You can create an. env file in the application's root directory that contains key/value pairs defining the project's required environment variables.

How do I see node environment variables?

If you have defined NODE_ENV variable then you should be able to see this by typing node in the command prompt which will open the node cell and then type process. env. NODE_ENV .


2 Answers

After reading and reading about this issue on the internet, the only way to resolve this issue for me was to declare the environment variable for the node execution:

GOOGLE_APPLICATION_CREDENTIALS="./key.json" node index.js

Because I was able to print the token from my server console, but when I was running the node application, the library was unable to retrieve the system environment value, but setting the variable for the execution, it was able to retrieve the value.

like image 68
m0rg4n Avatar answered Oct 06 '22 03:10

m0rg4n


Just to update this thread. Relative paths with GOOGLE_APPLICATION_CREDENTIALS now works fine with dotenv :)

Just store your service-account credentials as a file in your project and reference it relative to your env-file as a path. Then it should work fine :)

like image 22
Emil Wallgren Avatar answered Oct 06 '22 05:10

Emil Wallgren