[SOLVED] Authenticating a call to Google Cloud Vision using NPM

Hey guys,

I’m trying to authenticate a call to google’s cloud vision api using the service account credentials stored in a database.

On my backend cloudVision.jsw

import {getVision} from 'backend/config';
import vision from '@google-cloud/vision';

const client = new vision.ImageAnnotatorClient();

export async function create(url) {
  const token = await getVision();
  quickstart(url, token);
}

async function quickstart(url, token) {
 const GOOGLE_APPLICATION_CREDENTIALS = token;
 const [result] = await client.labelDetection(url);
 const labels = result.labelAnnotations;
 return console.log('Labels:');
}

On my backend config.jsw

import wixData from 'wix-data'; 

let options = {
 "suppressAuth": true
};

export async function getVision() {
 const response = await wixData.query("config").eq('title', 'vision').find(options);
 if(response.items.length === 0) return null;
 return JSON.parse(response.items[0].value);
}

The service account credentials seem to properly saved too.

On the Google Cloud API Documentation it is mentioned to “Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path of the JSON file downloaded”

I’m not sure I fully understand the above line because in the docs they say “If you don’t specify credentials when constructing the client, the client library will look for credentials in the environment.”

How can I send the credentials to authenticate the process using NPM.

If I use ‘fetch’ I need to place an API key as a parameter in the URL which works fine but I’m not sure how to authenticate using NPM.

Below is the image of the warning I’m getting

Thank you,
Shan

You can pass the credentials in the ImageAnnotatorClient constructor:

const client = new vision.ImageAnnotatorClient({ projectId, credentials })

credentials being an object that contains client_email and private_key.
See google cloud docs for further info: Node.js client library  |  Google Cloud

Worked like a charm! Thank you so much Ohad!

@shantanukumar847 Hi, would you please share your final code? I am trying to setup Google Cloud Storage and am running into the same issue. Trying to copy your code, but it doesnt seem to work, even with Ohad’s help. I must be doing something wrong somewhere

@mennyg19 Please make a new post. Follow our Community Guidelines while making one.