javascriptgoogle-cloud-platformgoogle-cloud-vision

How to add GOOGLE_APPLICATION_CREDENTIAL to Vision when hosted outside of GCP


I am trying to set up a serverless function on vercel, which uses Google Vision OCR to annotate the images. I am able to successfully do it locally but having a hard time figuring out how to add the GOOGLE_APPLICATION_CREDENTIALS on Vision OCR. I have stored the full service-key.json file in an environment called GOOGLE_APPLICATION_CREDENTIALS but that did not do anything.

Here is a brief overview of the code:

import vision from '@google-cloud/vision';
const vision = vision.ImageAnnotatorClient();
const analyze = async (req, res) => {
   const [result] = await client.textDetection(req.body.image);
   res.send(result)
} 

I have tried using google-auth-library and printing out an auth token so that I could call the Google REST API but that did not work either


Solution

  • After reading this blog, I was able to find that we can use the google-auth-library to configure the credentials manually without setting it up in the environment of the machine. And after a bit of digging around I also found that ImageAnnotatorClient takes an auth key for credentials. After patching it all together this was the final code that worked for me:

    import vision from '@google-cloud/vision';
    import  {GoogleAuth} from 'google-auth-library';
    
    const credentials = JSON.parse(process.env.GOOGLE_APPLICATION_CREDENTIALS);
    const auth = new GoogleAuth({credentials});
    const client = new vision.ImageAnnotatorClient({auth});
    
    const analyze = async (req, res) => {
       const [result] = await client.textDetection(req.body.image);
       res.send(result);
    }
    
    

    As mentioned in my question I saved the entire service-key.json file from google as plain string object in vercel env keys. Then I just parsed the whole env variable and added it to the auth generator.