According to the docs, using the service account key (the one you downloaded as a JSON file) is only for
Accessing private data on behalf of a service account outside Google
Cloud environments
These are used when:
- a user is not present to authenticate; or
- server-side requests which do not need a user.
For your use case I assume it's for the latter since you are using Dialogflow. Move this api call on your server side code for example by setting up a cloud function, lambda, or expressjs app running somewhere.
Do not run this request on React for 2 main reasons:
- React is Client-side which means users will have access to your source code including your private key. Big security risk.
- Dialogflow does not need a user to be authenticated to work.
To add the authentication on your request and use Dialog CX you may follow these steps which are loosely based from here. Take note, these steps are for when your server is running in or outside GCP. Google has a built in functionality if your code runs within GCP but I'll explain the one that works everywhere instead. All of this should be within your cloud function/lambda/expressjs app so if you are not familiar with that research how to set one up and how you can call this within React first.
- install dot-env and require it
npm install dotenv
or yarn add dotenv
- require dotenv within app
require('dotenv').config()
- Download private key json save it somewhere in your project folder)
- add
.env
to your .gitignore
file if it isn't there yet
- create
.env
file and add this inside it
GOOGLE_APPLICATION_CREDENTIALS="[PATH TO YOUR PRIVATE KEY]"
- install Dialogflow CX library
npm install @google-cloud/dialogflow-cx
- Use the Dialogflow library according to its docs here. The private service key will be automatically detected when using the library.
- On production, make sure to add
GOOGLE_APPLICATION_CREDENTIALS="[PATH TO YOUR PRIVATE KEY]"
as an environment variable to cloud function, lambda, docker or whatever you will be using.
As an added note, refresh your private keys and remove it from your React Project folder if you have already committed them to your github repo.