I have a NextJS / Typescript webapp. The backend of the webapp is supposed to call my Google Cloud Function, called "python-http-function" under project name "python-serverless-test-1". This is not a public function. I am testing my webapp locally, meaning with "npm run dev" and testing out calling my cloud function.
I am using ADC (Application Default Credentials), which finds the credentials in whatever current environment is being run. For local/development in this case, I provided user credentials to ADC by running the "gcloud auth application-default login" command, which created a file in $HOME/.config/gcloud/application_default_credentials.json. This file exists, I verified.
When I actually execute the call to python-http-function with the following code, however, it errors:
// source for this code: https://cloud.google.com/functions/docs/securing/authenticating#generating_tokens_programmatically
const targetAudience = 'https://us-west1-python-serverless-test-1.cloudfunctions.net/python-http-function'
const url = targetAudience;
const auth = new GoogleAuth();
const client = await auth.getIdTokenClient(targetAudience);
// Create a FormData object to hold the form data.
const formData = new FormData();
// Add the form data to the FormData object.
formData.append('pdf', 'data');
// Make the request to the Cloud function.
const res = await client.request({
url: url,
method: 'POST',
body: formData,
});
Error:
error Error: Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.
I verified that gcloud can find the JSON credentials file by running gcloud auth application-default print-access-token and seeing it print it out. What is going on here? What am I missing?
Thanks!
Hi @finnDiesel234xX,
Welcome to Google Cloud Community!
You may try this to resolve the issue of calling a Google Cloud Function from your local Next.js/TypeScript web app with Application Default Credentials (ADC):
Hope this helps!
Thank you for your response! To be clear, I have already created a service account, given it "editor" permission and attached it to my gen2 cloud function. Additionally, I have already fully set up ADC for local development following this.
However, even after setting
const targetAudience = 'https://us-west1-python-serverless-test-1.cloudfunctions.net/python-http-function'
const url = targetAudience;
const auth = new GoogleAuth();
const client = await auth.getIdTokenClient(targetAudience);
const formData = new FormData();
formData.append('pdf', 'data');
const res = await client.request({
url: url,
method: 'POST',
body: formData,
});
I am following this to a tee.
I also ran gcloud components update for good measure. Please let me know what other information I can provide.
I am completely lost on what is wrong here.